A function like: ng-click=“alert('Clicked')”

牧云@^-^@ 提交于 2019-12-10 14:57:18

问题


For a mockup I need a simple mechanism like

ng-click="alert('Clicked')"

but the code above is not working, can someone help me? I don't want to touch the Controller..


回答1:


As far as I know, ng-click works only within your $scope. So you would only be able to call functions, defined in your $scope itself. To use alert, you may try accessing the window element, just by using window.alert('Clicked').

EIDT: Thanks to Ibrahim. I forgot. You shouldn't be able to use window.alert, as far as you won't define:

$scope.alert = window.alert;

In this case, using alert('Clicked') in your ng-clicked directive should work. But at the end, this method would not solve your problem of not touching your controller.




回答2:


Refer to previous answer, ng-click = "alert('Hello World!')" will work only if $scope points to window.alert i.e

$scope.alert = window.alert;

But even it creates eval problem so correct syntax must be:

HTML

<div ng-click = "alert('Hello World!')">Click me</div>

Controller

$scope.alert = function(arg){
    alert(arg);
}



回答3:


As Neeraj mentioned, the accepted answer does not work. Add something like this to your controller to avoid an Illegal Invocation error:

$scope.alert = alert.bind(window);


来源:https://stackoverflow.com/questions/34899173/a-function-like-ng-click-alertclicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!