PenguinSource PenguinSource - 1 month ago 11
AngularJS Question

How can I access $event inside a directive?

I can't seem to pass it as an attribute!

I can add an ng-click="function($event)" and pass $event that way to a controller function, but I would like to access it inside a directive.

The ultimate purpose is to stopPropagation() and/or preventDefault() of an element inside a directive instead of in a controller.

EDIT: I will post code accordingly

<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/

Answer
    var myApp = angular.module('myApp',[]);
    myApp.directive('stopToggle', function(){
       return {
             link: function(scope, elem, attrs){
             elem.on('click', function(e){
                 e.stopPropagation();  // invalid function
                 e.preventDefault();    // invalid function
        })

     }
  }
});

Just pass event as an argument to the function inside of .on()

Comments