Reputation: 2982
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>
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
.
Upvotes: 14
Views: 17788
Reputation: 66
As others have said, ng-if has its own scope. What i want to say, it's a bad practice to put expressions in the view. The good practice is to have a scope function that's called within the view.
var ctrl = function($scope){
$scope.foo = false;
$scope.fn = fn;
function fn(){
$scope.foo = true;
}
/////
<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="fn()">Show foo</button>
</div>
<button ng-click="fn()">Show foo</button>
</div>
Upvotes: 0
Reputation: 2982
Ah, ng-if
creates a new scope! So, "there has to be a dot in the model name"!
Upvotes: 5
Reputation: 2589
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/
Upvotes: 26