0

Today, while i was playing around with angular i found something interesting. I can't find a proper explanation for this interaction. Any idea around that are welcome.

Case 1:

<div ng-show="boolean"> Show/Hide This </div>
<button ng-click="boolean = !boolean" />

Everything works as supposed. The button toggle the div. Hide or show at every click

Case 2:

<div ng-show="boolean"> Show/Hide This </div>
<div ng-if="showButton">
   <button ng-click="boolean = !boolean" />
</div>

In this case, even if showButton is true, and the button is visible, when i click, the first div doesn't change state.

Case 2:

<div ng-show="boolean"> Show/Hide This </div>
<div ng-if="showButton">
   <button ng-click="updateBoolean()" />
</div>

// And in controller $scope.updateBoolean = function(){ $scope.boolean = !$scope.boolean}

Here surprisely, when cliccking the button it does update the main div.


Update Ok, so short answer for future reference: The ng-if directive, like other directives creates a child scope.

Snick
  • 1,022
  • 12
  • 29
  • Sorry. There are numerous questions similar to this.. http://stackoverflow.com/questions/18342917/angularjs-ng-model-doesnt-work-inside-ng-if – PSL Dec 19 '14 at 22:45
  • 1
    Case #1 It creates a child scope, you can take a look [at this awesome answer as well](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482) Case #2 you are updating the actual controllers `$scope` itself. There is no implicit binding there as it happens onthe view. – PSL Dec 19 '14 at 22:47

0 Answers0