I am trying to understand a working code. It can build a very simple json data by adding name:value pairs one by one with GUI; by a custom directive and its link function, it builds a html template as the right hand of the image below:
What puzzles me is ng-model="$parent.keyName" in the highlighted part, as well as $parent.valueType, ng-model="$parent.valueName" in other part.
1) What does the $parent refer to (in the code or in the example of the above image)?
2) Is there a way to show the value of $parent or $parent.keyName in the console or by adding something (e.g., alert) in the program?
1) $parent refers to the parent scope (of any given scope). All scopes have a parent apart from $rootScope which is the top level scope. They can be created by any angular ng-* directive, including but not limited to ng-controller.
Generally speaking, it's considered bad practice to use $parent because it refers to the immediate parent scope which is subject to change. If the scope hierarchy does change (which it could do by adding a ng-* directive to a html element held in a custom directive template for example) then the hierarchy can be broken and $parent won't refer to the same scope that it once did.
2) Yes you can. In Chrome developer tools, if you Right Click > Inspect Element (as you have in the screen shot), you select the element. Then if you leave that element highlighted and go to the console tab and type:
angular.element($0).scope()
That returns the scope that the selected element resides in. Then if you type:
angular.element($0).scope().$parent()
That returns the parent scope of the scope that the selected element resides in. And for what it's worth you can also do:
angular.element($0).scope().$parent().$parent()
and keep going up the scope hierarchy.
Also check out the AngularJS Batarang chrome extension which allows you to look through the scopes in the Chrome Developer Tools.
What does this $parent refer to?
Parent refers to the scope of your parent controller. The image in your question doesn't give a clear picture so I will add an example for it.
<div ng-controller="EditorController">
<div ng-controller="ChildEditorController">
....
</div>
</div>
Assume you have a property called editorsList (array) in your EditorController (which is the parent controller here), you can do something like
<div ng-controller="EditorController">
<div ng-controller="ChildEditorController">
Editors Count: {{$parent.editorsList.length}}
</div>
</div>
So you can access the scope of your parent with the $parent.
Related
If I look at an HTML element in a complex angularJS application, and it has basic directive that evaluates an expression, e.g.
<li ng-class="{active: active}"></li>
How can I tell what controller the 'active' property belongs to, just by looking at the markup?
In this case, the active variable doesn't belong to a controller, it belongs to a scope. Scopes use prototype inheritance, so the variable could belong to any scope.
There are multiple directives that create scopes, so it might be hard to realize which scope it belongs to.
If you want to use a controller property, define an alias like ng-controller"myCtrl as alias" (should be unique), then, you can use the propertyas alias.myProperty and the alias will let you know inmediately which controller it belongs to.
In Chrome Developer Console you can grap the element using angular.element($0) method and some useful methods are
Controller : angular.element($0).controller()
Scope : angular.element($0).scope()
Chorme Extension : AngularJS Batarang https://chrome.google.com/webstore/detail/angularjs-batarang/ighdmehidhipcmcojjgiloacoafjmpfk?hl=en
I am completely new to AngularJS. In the code I am supposed to add a feature to I can see $scope.$parent I know about $scope. I also know that when I see a $ it means it is built-in angular. So I searched for it in Angular web site but
I did not have any luck finding anything about $Parent as a built-in service or factory or directive, etc...
Can anybody help me understand what it means. Also how I can get to an answer in their documentation when I run into something new?
The documentation for $parent is sparse, but you can find it referenced here at the very bottom of the page.
$scope.$parent refers to the $scope of the parent element. E.g. if you have an element with a controller nested within another element with it's own controller:
<div ng-controller="parentController">
... something in the parent element
<div ng-controller="childController">
... something in the child element
</div>
</div>
You can access variables attached to the parentController from the childController using $scope.$parent. and use them in the child element.
In angular, your scopes are all chained together. So, you can reference the scope "above" your immediate scope with $parent.
It's useful, for example, if you are working with a directive (or if you have a controller inside of another).
Preface
When I declare a directive under a controller, e.g.
<div ng-controller="MyController">
<my-directive></my-directive>
</div>
the directive inherits that controller's scope by default. This means if the controller defines
$scope.Heaven = "Free Beer"
then I have access to that within the directive's template via
{{ Heaven }}
Question
When declaring a directive within another directive, why doesn't the child inherit scope like it would if placed in a controller?
<my-parent-directive>
<my-child-directive>
</my-child-directive>
</my-parent-directive>
In short, if I declare a controller function for my-parent-directive and in it write:
$scope.Heaven = "Free Beer"
My child directive doesn't have access to this by default. Why is that?
(This assumes "scope: true" within the parent, no scope declaration in the child, and the child requiring the parent via "require: 'my-parent-directive')
Example codepens:
Directive wrapped in controller
Directive wrapped in directive
Question was modified after answer was given - the below is to preserve the reference
Directive wrapped in directive old
I am looking at the "Directive wrapped in directive old" on codepen. I think it is this you want to fix, but I'm not certain since your codepen is different to the example in your question (that's not a criticism, just clarification in case I am heading down the wrong route for you!)
However, if I am correct (and I am referring to the "Directive wrapped in directive old" on codepen for the rest of this answer):
You have declared the scope in myWrapper to be inherited ("scope: true"), therefore any properties that you add to the scope within myWrapper (such as "$scope.passdown = $attrs.passdown;") will only be visible to myWrapper.
You can remove the "scope: true" from myWrapper to share the scope between everything (not a great structure to use, but it will work) and you will solve your immediate problem, if I have understood you correctly. Or you can move the "passdown" property to a mutable object on the "parent" controller "$scope.abc = {passdown: ''};" for example. Then modify the value in myWrapper: "$scope.abc.passdown = $attrs.passdown;" and access it as "abc.passdown" in your interpolated expressions.
a bit of background:
changes to immutable types in "child" controllers/directive will make a copy of the property and those changes will never be seen on any other scope.
No scope declaration means shared scope - all components that share this scope too can see any properties / changes (to mutables) made on the scope. Tends to end up with closely coupled components that become very difficult to maintain.
"scope: true" means inherited scope and any additions made to the scope will only be visible to the inherting scope (ie the "child"). Changes to mutable properties in the parent will be visible to all other components that share this scope.
"scope: {...}" creates an isolated scope and provides a safe way to expose properties to parents and let the children modify those properties. This implementation is more work but you will end up with code that is easier to understand, maintain and share.
I hope this answer isn't too rambling and it helps you solve your problem.
Please help me understand scopes in AngularJS.
If I associate a controller within a directive (as opposed to within html), is it supposed to have any impact on the scope associated with the directive ?
How can I use ng-repeat after scope isolation ?
For e.g. here is an example: http://plnkr.co/edit/0flo5mru61r9h3H8kiW5?p=preview
ex1. If I comment out (div ng-controller="Ctrl")[line 40, 43] and instead uncomment (// controller: 'Ctrl')[line 35] within the directive, why aren't the same scopes/hierarchy created (as viewed in Batarang).
ex2. How can I run ng-repeat for instructorList and profList (separately) without changing the current controller and only playing around with the scope ?
I am not sure how to inspect plunkers in batarang, but.
If you do this, you're instantiating the controller twice: once on each directive element. Each time you instantiate it, you're creating a new scope. As such, you have two separate sibling scopes. You can see just from looking at the html that the heirarchy won't be the same as if you had them both within the same element that has its own scope. In the latter case, changes made by child element 1 would affect the same scope used by child element two.
It's not very clear what you mean here. ng-repeat should be done in html. You could put it in the template like this:
template: '<label ng-repeat="person in teacherList">{{person.id}}<input ng-model="person.name"><br></label>'
See this
I have a directive with an isolate-scope (so that I can reuse the directive in other places), and when I use this directive with an ng-repeat, it fails to work.
I have read all the documentation and Stack Overflow answers on this topic and understand the issues. I believe I have avoided all the usual gotchas.
So I understand that my code fails because of the scope created by the ng-repeat directive. My own directive creates an isolate-scope and does a two-way data-binding to an object in the parent scope. My directive will assign a new object-value to this bound variable and this works perfectly when my directive is used without ng-repeat (the parent variable is updated correctly). However, with ng-repeat, the assignment creates a new variable in the ng-repeat scope and the parent variable does not see the change. All this is as expected based on what I have read.
I have also read that when there are multiple directives on a given element, only one scope is created. And that a priority can be set in each directive to define the order in which the directives are applied; the directives are sorted by priority and then their compile functions are called (search for the word priority at http://docs.angularjs.org/guide/directive).
So I was hoping I could use priority to make sure that my directive runs first and ends up creating an isolate-scope, and when ng-repeat runs, it re-uses the isolate-scope instead of creating a scope that prototypically inherits from the parent scope. The ng-repeat documentation states that that directive runs at priority level 1000. It is not clear whether 1 is a higher priority level or a lower priority level. When I used priority level 1 in my directive, it did not make a difference, so I tried 2000. But that makes things worse: my two-way bindings become undefined and my directive does not display anything.
I have created a fiddle to show my issue. I have commented out the priority setting in my directive. I have a list of name objects and a directive called name-row that shows the first and last name fields in the name object. When a displayed name is clicked, I want it to set a selected variable in the main scope. The array of names, the selected variable are passed to the name-row directive using two-way data-binding.
I know how to get this to work by calling functions in the main scope. I also know that if selected is inside another object, and I bind to the outer object, things would work. But I am not interested in those solutions at the moment.
Instead, the questions I have are:
How do I prevent ng-repeat from creating a scope that prototypically inherits from the parent scope, and instead have it use my directive's isolate-scope?
Why is priority level 2000 in my directive not working?
Using Batarang, is it possible to know what type of scope is in use?
Okay, through a lot of the comments above, I have discovered the confusion. First, a couple of points of clarification:
ngRepeat does not affect your chosen isolate scope
the parameters passed into ngRepeat for use on your directive's attributes do use a prototypically-inherited scope
the reason your directive doesn't work has nothing to do with the isolate scope
Here's an example of the same code but with the directive removed:
<li ng-repeat="name in names"
ng-class="{ active: $index == selected }"
ng-click="selected = $index">
{{$index}}: {{name.first}} {{name.last}}
</li>
Here is a JSFiddle demonstrating that it won't work. You get the exact same results as in your directive.
Why doesn't it work? Because scopes in AngularJS use prototypical inheritance. The value selected on your parent scope is a primitive. In JavaScript, this means that it will be overwritten when a child sets the same value. There is a golden rule in AngularJS scopes: model values should always have a . in them. That is, they should never be primitives. See this SO answer for more information.
Here is a picture of what the scopes initially look like.
After clicking the first item, the scopes now look like this:
Notice that a new selected property was created on the ngRepeat scope. The controller scope 003 was not altered.
You can probably guess what happens when we click on the second item:
So your issue is actually not caused by ngRepeat at all - it's caused by breaking a golden rule in AngularJS. The way to fix it is to simply use an object property:
$scope.state = { selected: undefined };
<li ng-repeat="name in names"
ng-class="{ active: $index == state.selected }"
ng-click="state.selected = $index">
{{$index}}: {{name.first}} {{name.last}}
</li>
Here is a second JSFiddle showing this works too.
Here is what the scopes look like initially:
After clicking the first item:
Here, the controller scope is being affected, as desired.
Also, to prove that this will still work with your directive with an isolate scope (because, again, this has nothing to do with your problem), here is a JSFiddle for that too, the view must reflect the object. You'll note that the only necessary change was to use an object instead of a primitive.
Scopes initially:
Scopes after clicking on the first item:
To conclude: once again, your issue isn't with the isolate scope and it isn't with how ngRepeat works. Your problem is that you're breaking a rule that is known to lead to this very problem. Models in AngularJS should always have a ..
Without directly trying to avoid answering your questions, instead take a look at the following fiddle:
http://jsfiddle.net/dVPLM/
Key point is that instead of trying to fight and change the conventional behaviour of Angular, you could structure your directive to work with ng-repeat as opposed to trying to override it.
In your template:
<name-row
in-names-list="names"
io-selected="selected">
</name-row>
In your directive:
template:
' <ul>' +
' <li ng-repeat="name in inNamesList" ng-class="activeClass($index)" >' +
' <a ng-click="setSelected($index)">' +
' {{$index}} - {{name.first}} {{name.last}}' +
' </a>' +
' </li>' +
' </ul>'
In response to your questions:
ng-repeat will create a scope, you really shouldn't be trying to change this.
Priority in directives isn't just execution order - see: AngularJS : How does the HTML compiler arrange the order for compiling?
In Batarang, if you check the performance tab, you can see the expressions bound for each scope, and check if this matches your expectations.