Search code examples
angularjsangularjs-directiveangularjs-scopegoogle-chrome-devtools

"$parent" in multi-level directives


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:

enter image description here

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?


Solution

  • 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.