0

i am new in angular and learning. when i see the code from this url https://stackoverflow.com/a/19177773/6188148 then things is not clear.

see the code and tell me why model data can not be updated from child scope ?

<input type="text" ng-model="data">
<div ng-if="true">
    <input type="text" ng-model="data">
</div>     

see the below code again and tell me what special things is there for which model in parent scope is updating from inside the child scope ?

   <input type="text" ng-model="data.input">
    <div ng-if="true">
        <input type="text" ng-model="data.input">
    </div>

they use just data.input and parent data is updated from child scope....this is not clear. what is so special in .input keyword ?

please help me to understand how second example can update parent data just by .input keyword ?

also tell me when child scope gets created ? when we use ng-if or ng-show then ?

thanks

Community
  • 1
  • 1
Monojit Sarkar
  • 2,353
  • 8
  • 43
  • 94
  • See this - hopefully it will solve your doubts http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs – Gonzalo.- May 19 '17 at 14:35
  • You should read [this article](https://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html) and adopt a component architecture, along with its input-output boundary mandate. It'll instantly raise your Angular acumen and make scope confusion a thing of the past. – isherwood May 19 '17 at 14:43

1 Answers1

1

In the first example you posted, inside the ng-if, a new scope is created, and the input is bound to the child's scope variable called data. The outer input has its own scope, and its own data variable.

The following link explains whats going on in more detail. But in short, this behavior is because angularJs creates a new child scope when the ng-if directive is used. Angular scopes use prototypical inheritance. To by pass this situations, we can leverage the fact that Javascript objects are pass by reference.

"If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property."

The quick answer from: https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance

tpdietz
  • 1,358
  • 9
  • 17