Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 将$event传递给ng click,但未定义事件_Angularjs - Fatal编程技术网

Angularjs 将$event传递给ng click,但未定义事件

Angularjs 将$event传递给ng click,但未定义事件,angularjs,Angularjs,在我的控制器中,单击事件后,我向页面添加一个指令,该指令将能够调用controllerFunc $scope.addDirective = function(e, instance){ $scope.instance = instance; $(e.currentTarget.parentElement).append($compile('<my-directive myfunc="controllerFunc($event)" mydata={{instance}}/>

在我的控制器中,单击事件后,我向页面添加一个指令,该指令将能够调用
controllerFunc

$scope.addDirective = function(e, instance){
   $scope.instance = instance;
   $(e.currentTarget.parentElement).append($compile('<my-directive myfunc="controllerFunc($event)" mydata={{instance}}/>')($scope));
}
当我单击相关的div时,
controllerFunc
在控制器中被调用,但该事件被称为
undefined

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

在这种情况下,是否有方法通过
ng click
传递事件(即,我使用ng click事件向dom添加了一个模板?它似乎应该可以工作(因为click事件触发函数)但是在
controllerFunc

中没有事件,在控制器函数中,注意参数的名称

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

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

这是假设您已将原来的$event更改为event。

我不知道div元素,但如果您对anchor()元素执行ng click,则可能遇到此问题。要防止此问题,应使用event.preventDefault()click设置其onclick属性。单击此:

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

这将阻止在ng click有机会执行之前导航到链接


谢谢。

试试这个
ng click=“myfunc({$event:$event})
。它应该可以工作。最好在控制器中使用preventDefault(),如果模板更改,它会使dom更清晰,并使可维护的代码更清晰。在视图中,$event.preventDefault()取消($event)或者在代码函数中返回false我不理解,也许代码片段会有所帮助。谢谢。
ng-click="myfunc({event: $event})"
<a href="#" onclick="event.preventDefault()" ng-click="Cancel($event)">Cancel</a>