Javascript – bound element inside ngIf does not update binding

angularjsangularjs-directivejavascript

I have written a angularjs directive.
in this directive's template I have added an ngIf directive and within it I display an input that is bound to my directive's scope.

<div ng-if="bool"><input ng-model="foo"></div>

I noticed, after a lot of trial and error that the ngIf directive cause the model to not get updated when the input text is changed. If I change it to ngShow everything works as expected.

I am looking for an explanation of this difference

I have created a jsfiddle here

Best Answer

It's happening because ngIf creates a new child scope, so if you want to bind to the same scope as the other inputs, we can go one level down with $parent. Check here to understand more about scope inheritance

  angular.module('testApp', [])
  .directive('testDir', function () {
    return {
      restrict: 'A',
      template: '<input ng-model="foo"><input ng-model="foo">' +
         '<div ng-if="bool"><input ng-model="$parent.foo"></div>',
      link: function (scope, elem, attrs) {
        scope.foo = "bar";
        scope.bool = true;       
      }
    }
  });

Take a look to new jsfiddle