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