Passing $ event to ng-click, but the event is undefined

In my controller, after the click event, I add a directive to the page that will be able to call controllerFunc

 $scope.addDirective = function(e, instance){ $scope.instance = instance; $(e.currentTarget.parentElement).append($compile('<my-directive myfunc="controllerFunc($event)" mydata={{instance}}/>')($scope)); } 

In my directive, I configured it so that controllerFunc is called in the click event (via myfunc: &), and I'm trying to pass the click event through $event

 app.directive('myDirective',function(){ return { restrict: 'AE', scope: { mydata: '@', myfunc: "&" }, template: '<div class="row"><div class="col-4" ng-click="myfunc($event)"></div></div>', link: function(scope, elem, attrs){ //ommitted } } } 

When I click on the appropriate div, controllerFunc is called in the controller, but the event is called undefined .

  $scope.controllerFunc = function(e){ //called on the click event but e is undefined } 

Is there a way to pass the event using ng-click in this situation (for example, where did I add the template in dom with the ng-click event? It seems to work (since the click event triggers the function), but there is no event in controllerFunc

+7
angularjs
source share
2 answers

Inside your controller function there is an argument name

 '<my-directive myfunc="controllerFunc($event)" mydata={{instance}}/>')($scope)); 

This is currently "$ event", it is not a function that uses the $ event keyword, it is just a function with an argument, and you have to provide it. I would change the $ event event to an event for clarity.

Now, after you have done this, you can go to your directive, and in the template for your directive you set the ng-click parameter in this way

 template: '<div class="row"><div class="col-4" ng-click="myfunc($event)"></div></div>', 

This ng-click will call the function and, but to bind to the corresponding parameter you need to use a slightly different syntax and match the name of the parameter that it should match, therefore

 ng-click="myfunc($event)" 

becomes

 ng-click="myfunc({event: $event})" 

Suppose you change the original event of $ event to an event.

+11
source share

I don't know about the div element, but if you do ng-click against the anchor () element, you may run into this problem. To prevent it, you must set its onclick property with event.preventDefault () to do this:

 <a href="#" onclick="event.preventDefault()" ng-click="Cancel($event)">Cancel</a> 

This will prevent link navigation before ng-click gets a chance to complete.

Thanks.

+2
source share

All Articles