如何将事件对象传递给angularJs指令中的方法

时间:2017-11-14 06:33:25

标签: jquery angularjs angularjs-directive

我开发了一个模态指令。我希望通过按钮点击模式获取触发的事件。我在下面给出了angularJs代码,

var myModal = angular.module('myModal', []);
myModal.controller('mymodalcontroller', function ($scope) {
    $scope.header = 'Put here your header';
    $scope.body = 'Put here your body';
    $scope.footer = 'Put here your footer';

    $scope.myRightButton = function () {
            // I want the event here to perform some task
            alert('!!! first function call!');
    };
});
myModal.directive('modal', function () {
    return {
        restrict: 'EA',
        scope: {
            title: '=modalTitle',
            header: '=modalHeader',
            body: '=modalBody',
            footer: '=modalFooter',
            callbackbuttonleft: '&ngClickLeftButton',
            callbackbuttonright: '&ngClickRightButton',
            handler: '=lolo'
        },
        templateUrl: 'partialmodal.html',
        transclude: true,
        controller: function ($scope) {
            $scope.handler = 'pop'; 
        },
    };
});

我想要event函数中的$scope.myRightButton对象。

partialmodal.html代码如下,

<div id="{{handler}}" class="modal fade">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title">{{header}}</h4>
        </div>
        <div class="modal-body">

            <p class="text-warning">{{body}}</p>

        </div>
        <div class="modal-footer">

            <p class="text-left">{{footer}}</p>

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" data-ng-click="callbackbuttonright()">Launch Alert</button>

        </div>
    </div>
</div>

如何从控制器获取Launch Alert按钮单击事件?

我的模态实现如下,

 <div ng-controller="mymodalcontroller">
  <modal lolo="modal1" modal-body="body" modal-footer="footer" modal-header="header" data-ng-click-right-button="myRightButton()"></modal>
  <a href="#{{modal1}}" role="button" class="btn btn-success" data-toggle="modal">Launch Demo Modal</a>
</div>

1 个答案:

答案 0 :(得分:0)

<强> HTML

$event作为参数传递到data-ng-click-right-button="myRightButton($event)"

由于您的partialmodal.html模板具有on-click方法,因此您需要从$event传递<{1}}

<强> partialmodal.html

<button type="button" class="btn btn-primary" data-ng-click="callbackbuttonright($event)">Launch Alert</button>

<强>控制器

$scope.myRightButton = function (event) {
    // I want the event here to perform some task
    console.log(event);   
    alert('!!! first function call!');
};