看起来很简单,但我无法从我的指令中获取$event.当从cb-click调用test时,$event是未定义的,但在指令之外(通过html),它是事件对象.
如果我使用链接功能(不包括在我的小提琴中),我可以获得$event,但我无法在正确的范围内解析/ $eval它.
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'; } });
您需要在指令中使用此语法:
原文链接:https://www.f2er.com/angularjs/142125.htmlng-click="cbClick({ev: $event,b:\'a\'})
使用此HTML:
cb-click="test(ev,b)"
从directives page开始,“指令定义对象”部分:
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 thelocalFn
aslocalFn({amount: 22})