Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model does not update within ng-if

I've got a strange behavior in an angular application and I don't know if that's a bug or a known limitation:

'use strict';

var ctrl = function ($scope) {
    $scope.foo = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ctrl">
  foo: {{foo}}
  <div ng-if="foo" style="background-color: #f00;">
    <p>foo</p>
  </div>
  <div ng-if="!foo">
    <br/><button ng-click="foo = true;">Show foo</button>
  </div>
  <button ng-click="foo = true">Show foo</button>
</div>

http://jsfiddle.net/78R52/

I would expect that clicking one of the buttons would set foo = true, but clicking the first button (within the ng-if="!foo") doesn't change the model.

Tested version is 1.2.1.

like image 334
stofl Avatar asked Nov 19 '13 09:11

stofl


People also ask

What is the difference between * ngIf and ngIf?

What is the difference between ngIf and *ngIf in Angular? ngIf is the directive. Because it's a structural directive (template-based), you need to use the * prefix to use it into templates. *ngIf corresponds to the shortcut for the following syntax (“syntactic sugar”):

Which is better Ng-if or NG-show?

ng-if can only render data whenever the condition is true. It doesn't have any rendered data until the condition is true. ng-show can show and hide the rendered data, that is, it always kept the rendered data and show or hide on the basis of that directives.

How do you change the value of an NG model?

If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.

What is the use of NG-if directive?

Definition and Usage The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.


1 Answers

ng-if has its own scope, so you need to use:

<br/><button ng-click="$parent.foo = true;">Show foo</button>

Updated fiddle: http://jsfiddle.net/78R52/1/

like image 113
thebenedict Avatar answered Oct 11 '22 02:10

thebenedict