What is $ parent in AngularJS?

3

I'm reviewing a PR from a colleague and I came across the use of $parent , I read a little in the documentation of the angle, but I can not understand what it does. Home Is it used inside a dialog created inside another, would it have any relation to have as keyword the word parent ?
Here are my questions about your usage.

  • In layman's terms, what does $parent do?
  • What is the occasion where the use of $parent
  • Because it is used since both dialogs split the controller, should not their scopes be the same already?
asked by anonymous 14.06.2017 / 19:45

1 answer

5

$parent is a way to access data from previous scopes in the hierarchy from isolated scopes.

Example:

angular.module('myApp', [])
.controller('myController', function($scope){
  $scope.dados = "dados!";
})
.directive("dirScope", function () { 
  return { scope: true, template: '<div>dirScope: {{dados}}</div>'};
})
.directive("dirNoScope", function () {
  return { scope: {}, template: '<div>dirNoScope: {{dados}}</div>'};
})
.directive("dirNoScopeParent", function () {
  return { scope: {}, template: '<div>dirNoScopeParent: {{$parent.dados}}</div>' };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script><divng-app="myApp">
  <div ng-controller='myController'>
  {{dados}}
  
  <dir-scope></dir-scope>
  <dir-no-scope></dir-no-scope>
  <dir-no-scope-parent></dir-no-scope-parent>
    
  </div>
</div>

When you click Run you will notice that the dirScope and dirNoScopeParent directives correctly display the value of dados - but dirNoScope

dirScope is able because its scope is shared with the parent element, via scope: true setting.

dirNoScope , in turn, has its scope isolated - scope: {} - and therefore does not inherit from the parent scope.

dirNoScopeParent also has its scope isolated by scope: {} . However, the value of dados can be properly read because $parent is used in the template definition, escaping the limitation of the scope and thus reaching the desired value.

    
14.06.2017 / 20:11