angularjs scope(the crux): parent child scope having model(with and without 'dot')

前端 未结 2 940
無奈伤痛
無奈伤痛 2021-01-21 21:04

Example WITHOUT \'dot\' http://jsfiddle.net/CmXaP/168/

Pa
相关标签:
2条回答
  • 2021-01-21 21:26

    As we know child scope creation in angularjs is based on prototypal inheritance. Therefore, while while displaying the values it searches the current scope(child scope) for 'name', here in this case both child scopes does not have any 'name' variable, so it will be read from parent scope and will display in each child scope.

    Basic rule: So reading a value will search the parents if it is not found.

    But while writing a value always writes directly to the object, even if it is also defined higher up.

    If one of child1 or child2 tries to write to parent's scope, it will work only on object var(non-primitive) types. The reason for this is that object(non-primitive) types are passed by reference. In other way when it tries to write normal variable(primitive) it will write into the current scope(in case A) child scope), hence it is not getting reflected in other scopes.

    0 讨论(0)
  • 2021-01-21 21:41

    Angular creates a child scope for each controller. Having a dot in the model doesn't change anything to that.

    When you enter 'foo' in a field with ng-model="name", here's what angular does with the scope of the current controller:

    scope.name = 'foo';
    

    If there was already a name field in the parent scope, it's unaffected. So you end up with

    parentScope ---> name --> 'some previous value'
    scope ---------> name --> 'foo'
    

    Now when you enter 'foo' in a field with ng-model="user.name", here's what angular basically does with the scope of the current controller:

    if (!angular.isDefined(scope.user)) {
        scope.user = {};
    }
    scope.user.name = 'foo';
    

    So, if the parent scope already had a user, with a name attribute having the value 'some previous value', you end up with

    parentScope --> user ------> name ----> 'foo
                     ^
    scope ----------/
    

    Why? Because the scope prototypically inherits from the parent scope, so when evaluating scope.user, JavaScript doesn't find a user attribute on the scope object, so it looks for it on the prototype (the parent scope), and finds it. Both the parent and the child thus share a single user object, and scope.user.name = 'foo' changes the name attribute of this shared object.

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