我似乎无法将其作为属性传递!
我可以添加ng-click ="功能($ event)"并将$ event传递给控制器函数,但我想在指令中访问它。
最终目的是在指令内而不是在控制器中对一个元素stopPropagation()和/或preventDefault()。
编辑:我会相应地发布代码
<div ng-app="myApp" ng-controller="MyCtrl">
<button stop-toggle ng-click="testFunction($event)">
click me
</button>
Hello, {{name}}!
</div>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.testFunction = function($event){
console.log("you can access the event here:", $event);
$event.stopPropagation();
}
}
myApp.directive('stopToggle', function(){
return {
link: function(scope, elem, attrs){
elem.bind('click', function(){
console.log("how do i access the $event here??");
// elem.stopPropagation(); // invalid function
// elem.preventDefault(); // invalid function
})
}
}
});
答案 0 :(得分:0)
var myApp = angular.module('myApp',[]);
myApp.directive('stopToggle', function(){
return {
link: function(scope, elem, attrs){
elem.on('click', function(e){
e.stopPropagation();
e.preventDefault();
})
}
}
});
只需将事件作为参数传递给.on()
中的函数