ng-click 不会触发 javascript 全局函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16745480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-click does not fire javascript global function
提问by Michael Soulier
I'm new to AngularJS, and I've put an ng-click on a radio button generated by ng-repeat, and the click event refuses to fire. If I use a simple onclick, that does work though.
我是 AngularJS 的新手,我在 ng-repeat 生成的单选按钮上放置了一个 ng-click,并且单击事件拒绝触发。如果我使用简单的 onclick,那确实有效。
This works, and I see the alert:
这有效,我看到警报:
<div class="span2 left-justify"
ng-repeat="choice in physicalmode_choices">
<input type="radio"
name="physical_layer"
value="{{ choice.private }}"
onclick="alert('foo')"
required
ng-model="$parent.networkoptions.physicalmode" />
<span ng-bind="choice.public"></span>
</div>
But this does not:
但这不会:
<div class="span2 left-justify"
ng-repeat="choice in physicalmode_choices">
<input type="radio"
name="physical_layer"
value="{{ choice.private }}"
ng-click="alert('foo')"
required
ng-model="$parent.networkoptions.physicalmode" />
<span ng-bind="choice.public"></span>
</div>
Can I not do this with an ng-click? Or am I misunderstanding what an "expression" is?
我不能通过 ng-click 执行此操作吗?还是我误解了“表达”是什么?
Thanks, Mike
谢谢,迈克
回答by cakey
To clarify DerekR's answer.
澄清德里克的答案。
When angular sees
当角看到
ng-click='alert("test")'
it looks for
它寻找
$scope.alert
which is likely to be undefined.
这可能是未定义的。
You need to provide a proxy method on the scope, or possibly even rootscope.
您需要提供作用域上的代理方法,甚至可能是 rootscope。
For example:
例如:
$rootScope.log = function(variable) {
console.log(variable);
};
$rootScope.alert = function(text) {
alert(text);
};
See: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED#scopemethods
请参阅:http: //deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED#scopemethods
回答by DerekR
When you call something inside of an ng-click the parsing service evaluates expressions against the scope rather than the global window object.
当您在 ng-click 中调用某些内容时,解析服务会针对范围而不是全局窗口对象评估表达式。
If you wanted to do an alert inside of an ng-click then could write a method on the scope or parent scope that in turn calls the alert.
如果您想在 ng-click 内执行警报,则可以在作用域或父作用域上编写一个方法,然后依次调用警报。
回答by Pablo
I created this jsFiddle to show how it works.
我创建了这个 jsFiddle 来展示它是如何工作的。
<li ng-repeat="menu in menus" >
<a ng-click="test(menu)">click me</a>
</li>