bound element inside ngIf does not update binding

前端 未结 3 979
滥情空心
滥情空心 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:


    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.

提交回复
热议问题