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

Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59
  • What do you use `ng-if` for? – Muhammad Reda Nov 20 '14 at 12:28
  • 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. – Sebastian Barth Nov 20 '14 at 12:30
  • BTW: I also ran into this [bug](http://forum.ionicframework.com/t/ng-click-wrapped-by-label-doesnt-work-when-migrated-from-beta-8-to-beta-11/8000/3) (Ionic?) which made the ng-click useless if a – Sebastian Barth Nov 20 '14 at 13:07
  • Possible duplicate of [AngularJS: ng-if not working in combination with ng-click?](http://stackoverflow.com/questions/19812116/angularjs-ng-if-not-working-in-combination-with-ng-click) – Motin Feb 16 '17 at 09:29

5 Answers5

17

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

Fiddle

Muhammad Reda
  • 26,379
  • 14
  • 93
  • 105
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.

Viktor
  • 257
  • 1
  • 5
  • It's very easy to bloat your code with $parent, for example chaining $parent calls ($parent.$parent.property). – Viktor Nov 20 '14 at 13:26
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

pablochan
  • 5,625
  • 27
  • 42
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

dlac
  • 315
  • 2
  • 9
0

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

mahsa k
  • 555
  • 6
  • 9