javascript ng-click 不适用于 ng-if
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27039631/
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 not working with ng-if
提问by Sebastian Barth
Why does the second button not work, when ng-if is used?
使用 ng-if 时,为什么第二个按钮不起作用?
I want to realize a button that is present only when the model value is set / not ""/ not null.
我想实现一个仅在模型值设置/不“”/不为空时才存在的按钮。
Template:
模板:
<input type="text" ng-model="blub"/>
<br/>
<button ng-click="blub = 'xxxx'">X</button>
<br/>
<button ng-click="blub = 'yyyy'" ng-if="blub.length">Y</button>
Controller:
控制器:
angular.module('test', [])
.controller('Main', function ($scope) {
// nothing to do here
});
To play around: JSFiddle
玩转: JSFiddle
回答by Viktor
It doesn't work because ng-if is creating a new scope and interpreting your blub = 'yyyy' as defining a new local variable in the new scope. You can test this by putting the second button to:
它不起作用,因为 ng-if 正在创建一个新范围并将您的 blub = 'yyyy' 解释为在新范围中定义一个新的局部变量。您可以通过将第二个按钮置于以下位置来测试:
<button ng-click="$parent.blub = 'yyyy'" ng-if="blub.length">Y</button>
However $parent is an ugly feature.
然而 $parent 是一个丑陋的功能。
回答by pablochan
The button doesn't work because of the nested scope created by ng-if
. The blub
bound to the second button is not the same blub
that's bound to the first one.
由于由ng-if
. 在blub
绑定到第二个按钮是不一样的blub
一个绑定到第一个。
You can use ng-show
instead of ng-if
, since it uses its parent's scope, but that's just avoiding the problem instead of solving it. Read about nested scopesso you can understand what actually happened.
您可以使用ng-show
而不是ng-if
,因为它使用其父级的范围,但这只是在避免问题而不是解决问题。阅读嵌套作用域,以便您了解实际发生的情况。
Also, check this out: fiddle
另外,看看这个:小提琴