AngularJS getting $event from a directive

2020-03-01 20:32发布

问题:

Seems pretty simple, but I can't get $event to bubble up from my directive. When test gets called from cb-click, $event is undefined, but outside of a directive (via html), it's the event object.

If I use a linking function (not included in my fiddle), I can get $event, but I can't $parse/$eval it against the right scope.

http://jsfiddle.net/langdonx/KgcGY/

<div ng-app="app" ng-controller="x">
    <!-- via directive -->
    <checkbox cb-model="y" cb-click="test($event, b)"></checkbox>
    <!-- via html -->
    <div><input id="c2" type="checkbox" ng-model="x" ng-click="test($event, 'a')"> <label for="c2">{{x}}</label></div> 
</div>

-

var app = angular.module('app', []);

app.directive('checkbox', function ($parse) {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            cbModel: '=',
            cbClick: '&'
        },
        template: '<div><input id="c1" type="checkbox" ng-model="cbModel" ng-click="cbClick($event, \'a\')"> <label for="c1">{{cbModel}}</label></div>'
    };
});

app.controller('x', function x($scope) {
    $scope.x = true;
    $scope.y = true;
    $scope.test = function (ev, b) {
        console.log('test called, ev is', ev, 'b is', b);
        return 'xyz';
    }
});

回答1:

You need to use this syntax inside your directive:

ng-click="cbClick({ev: $event, b:\'a\'})

With this HTML:

cb-click="test(ev, b)"

Fiddle

From the directives page, section "Directive Definition Object":

Often it's desirable to pass data from the isolated scope via an expression and to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22})