如何在指令中访问$ event?

时间:2016-10-08 15:59:07

标签: angularjs angularjs-directive

我似乎无法将其作为属性传递!

我可以添加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
        })

     }
  }
});

http://jsfiddle.net/Lvc0u55v/10656/

1 个答案:

答案 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()

中的函数