javascript tutorial - [Solved-5 Solutions] Nuances of scope prototypal / prototypical inheritance in AngularJS - javascript - java script - javascript array
Problem:
What are the nuances of scope prototypal / prototypical inheritance in AngularJS ?
Solution 1:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.
As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are
- define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
- use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
- define a function on the parent scope, and call it from the child (not always possible)
New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so the problem often shows up when these directives are involved. Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
Solution 2:
Solution 3:
Suppose we have in our controller:
And in our HTML:
Solution 4:
First we create "Parent" object function
Then add a prototype to "Parent" object function
Create "Child" object function
Assign child prototype (Make child prototype inherit from parent prototype)
Assign proper "Child" prototype constructor
Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects
Initiate Parent (dad) and Child (son) objects.
Call Child (son) changeProps method
- Check the results.
- Parent primitive property did not change
Child primitive property changed (rewritten)
Parent and Child object.one properties changed
Solution 5:
It doesn't look up the chain, but when you set