bound element inside ngIf does not update binding

前端 未结 3 964
滥情空心
滥情空心 2020-12-25 12:02

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.

相关标签:
3条回答
  • 2020-12-25 12:21

    This happens because you use a primitive on the scope.

    ngIf creates a new child scope and it shadows the value from the parent scope.

    Use the dot notation instead:

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

    From Understanding Scopes wiki:

    Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope.

    It doesn't work the way most people expect it should work. What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works.

    New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view and ng-include all create new child scopes, so the problem often shows up when these directives are involved.

    This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models.

    0 讨论(0)
  • 2020-12-25 12:31

    Define foo as an object with properties. This all has to do with javascript prototypical inheritance. See your modified jsfiddle.

     angular.module('testApp', [])
      .controller('MyController',function($scope){
          $scope.foo = {bool: true};
      })
      .directive('testDir', function () {
        return {
          restrict: 'A',
          template: '<input ng-model="foo.x"><input ng-model="foo.x"><div ng-if="foo.bool"><br/>changing me does not update the other inputs because i am in an ngIf if in ngShow all works just fine<input ng-model="foo.x"></div>',
          link: function (scope, elem, attrs) {
            scope.foo.x = "bar";
            scope.foo.bool = true;       
          }
        }
      });
    

    For a detailed info see this video.

    0 讨论(0)
  • 2020-12-25 12:32

    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

    0 讨论(0)
提交回复
热议问题