ng-click not working with ng-if
Asked Answered
P

5

11

Why does the second button not work, when ng-if is used?

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

Prady answered 20/11, 2014 at 12:27 Comment(4)
What do you use ng-if for?Hanoi
It checks the scope variable blub for a length != 0. Then it shows me a button. In the end I want to use that button to unset the variable. This allows the user to remove the value completely. E.g. blub is a part of an object and should only be set if the user wants it to set.Prady
BTW: I also ran into this bug (Ionic?) which made the ng-click useless if a <label> is wrapped around-Prady
Possible duplicate of AngularJS: ng-if not working in combination with ng-click?Rizas
H
17

Use ng-show Instead of ng-if. That should work.

Fiddle

Hanoi answered 20/11, 2014 at 12:30 Comment(5)
How did you make the Fiddle button?Prady
Wrap the link between <kbd></kbd> tag :).Hanoi
Cool, I was about to give answer that use ng-show but was unable to make make fiddle of angular code :(Garges
@MuhammadReda It's beautiful, but really not semantic at all. Please stop doing that.Deucalion
I think it should be comment, not a answerBourgogne
S
8

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:

<button ng-click="$parent.blub = 'yyyy'" ng-if="blub.length">Y</button>

However $parent is an ugly feature.

Spoondrift answered 20/11, 2014 at 12:46 Comment(1)
It's very easy to bloat your code with $parent, for example chaining $parent calls ($parent.$parent.property).Spoondrift
B
5

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.

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 scopes so you can understand what actually happened.

Also, check this out: fiddle

Buie answered 20/11, 2014 at 12:48 Comment(0)
E
3

Try putting a magic dot 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

Emikoemil answered 14/12, 2015 at 16:49 Comment(0)
A
0

you can use : [hidden]="!expression"

Alkaline answered 31/8, 2021 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.