What is $Parent in Angularjs?

Asked

Viewed 1,318 times

3

I’m reviewing a colleague’s PR and came across the use of $parent, I read a little in the documentation of angular, but I can’t understand what it does.
It is used within a dialog created within another, it would have some relationship to have as keyword the word parent?
Follow my doubts about its use.

  • In layman’s terms, what $parent ago?
  • What is the occasion where the use of $parent
  • Because it is used since both dialog’s divide the controller, their Scopes should not be the same already?

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>
<div ng-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>

By clicking on Execute you will notice that the directives dirScope and dirNoScopeParent correctly display the value of dados - however dirNoScope nay.

dirScope is capable because its scope is shared with the parent element, via definition scope: true.

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

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 scope limitation and thus achieving the desired value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.