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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:51:41  来源:igfitidea点击:

ng-click not working with ng-if

javascriptangularjsangularjs-ng-clickangular-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 Muhammad Reda

Use ng-showInstead of ng-if. That should work.

使用ng-show代替ng-if。那应该有效。

Fiddle

Fiddle

回答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 blubbound to the second button is not the same blubthat's bound to the first one.

由于由ng-if. 在blub绑定到第二个按钮是不一样的blub一个绑定到第一个。

You can use ng-showinstead 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

另外,看看这个:小提琴

回答by dlac

Try putting a magicdot on the variable

尝试在变量上放置一个魔法

<input type="text" ng-model="bl.ub"/>
<br/>
<button ng-click="bl.ub = 'xxxx'">X</button>
<br/>
<button ng-click="bl.ub = 'yyyy'" ng-if="bl.ub.length">Y</button>

jsfiddle

提琴手