我有一个带有模板的指令(基本上是两个带有 ng-click 的按钮)。
app.directive('foo', function(){
return {
scope: {
onNext: "=",
onPreviousClick: "="
},
restrict: "E",
template: "<button ng-click='onPreviousClick($event)'>Prev</button> <button ng-click='onNextClick($event)'>Next</button>",
link: function($scope){
$scope.onPreviousClick = function(){
console.log("Prev click event from directive");
}
$scope.onNextClick = function(){
console.log("Next click event from directive");
}
}
}
});
现在,当我使用该指令时,我想将点击处理程序设置为在 Controller 中工作。
<foo on-previous-click="ctrl.onPreviousClick($event)"></foo>
app.controller("myController", function($scope){
this.onPreviousClick = function(){
console.log("Prev click from the controller.");
}
});
基本上我希望点击事件“传递”指令和 Controller 。我希望两个事件处理程序都为上一个按钮点击而触发。
但我只能让一个或另一个点击处理程序工作。如果我注释掉我的指令处理程序, Controller 就会工作,反之亦然。
最佳答案
理想情况下,您应该使用函数绑定(bind) &
而不是双向绑定(bind),并且也只从指令处理程序进行调用。
return {
scope: {
onNext: "&",
onPreviousClick: "&"
},
并通过键值对将事件传递给绑定(bind)的处理程序,即
$scope.onPrev({$event: $event });
因此您可以在链接函数中执行此操作:
$scope.onPrevClick = function($event) {
console.log("Prev click event from directive");
$scope.onPrev({
$event: $event
});
}
或在模板本身上。
<button ng-click='onPrevClick($event);onPrev({$event:$event})'>Prev</button>
演示
angular.module('app', []).controller('ctrrl', function($scope) {
this.onPreviousClick = function() {
console.log("Prev click from the controller.");
}
this.onNextClick = function() {
console.log("Next click from the controller.");
}
}).directive('foo', function() {
return {
scope: {
onNext: "&",
onPrev: "&"
},
restrict: "E",
template: "<button ng-click='onPrevClick($event)'>Prev</button> <button ng-click='onNextClick($event); onNext({$event:event})'>Next</button>",
link: function($scope) {
$scope.onPrevClick = function($event) {
console.log("Prev click event from directive");
$scope.onPrev({
$event: $event
});
}
$scope.onNextClick = function() {
console.log("Next click event from directive");
}
}
}
});;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>
<div ng-app="app" ng-controller="ctrrl as ctrl">
<foo on-prev="ctrl.onPreviousClick($event)" on-next="ctrl.onNextClick($event)"></foo>
</div>
关于javascript - 如何在指令和 Controller 中处理模板 ng-click?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27847847/