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