gpt4 book ai didi

AngularJS 从指令获取 $event

转载 作者:行者123 更新时间:2023-12-02 10:20:53 26 4
gpt4 key购买 nike

看起来很简单,但我无法让 $event 从我的指令中冒出来。当从 cb-click 调用 test 时,$event 未定义,但在指令之外(通过 html),它是事件对象。

如果我使用链接函数(未包含在我的 fiddle 中),我可以获得$event,但我无法在正确的范围内对其进行$parse/$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';
}
});

最佳答案

您需要在指令中使用此语法:

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

使用此 HTML:

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

Fiddle

来自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 the localFn as localFn({amount: 22})

关于AngularJS 从指令获取 $event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16042863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com