Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-click not working with ng-if

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

like image 527
Sebastian Barth Avatar asked Nov 20 '14 12:11

Sebastian Barth


4 Answers

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

Fiddle

like image 177
Muhammad Reda Avatar answered Nov 03 '22 01:11

Muhammad Reda


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.

like image 41
Viktor Avatar answered Nov 02 '22 23:11

Viktor


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

like image 21
pablochan Avatar answered Nov 03 '22 01:11

pablochan


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

like image 20
dlac Avatar answered Nov 03 '22 01:11

dlac