There are three types of scopes used in a Custom Directive:-
1. Shared scope
2. Inherited scope
3. Isolated scope
1. Shared scope:-
Directives share the scope within that controller, in a shared scope. Since a new scope is not created by the directive, so there is no inheritance here. Therefore we should not use this when directive is intended to use as a reusable component. It is also the default scope.
Lets see an example:-
App.controller(EgController', ['$scope', function ($scope) {
$scope.student = {
name: hello,
age: 32,
subject: [
"maths,
computers
]
}
$scope.setGrade = function (student) {
student.grade = "A+"
}
}]);
lets make a custom directive
App.directive(egDirective', function () {
return {
template: "
{{student.name}} is {{student.age}} years old !!
",
replace: true,
restrict: 'E',
controller: function ($scope) {
console.log($scope);
}
}
});
In this code snippet any changes we do to the properties in the directive would be reflected to the controller and vice-versa.
The problem with the shared scope is as mentioned above we are not able to pass data explicitly to the directive.
2.Inherited scope:
The directive inherits the scope of the controller,in the inherited scope.We just have to set true to the value of the scope property. After that Angularjs creates a new scope object and this object is prototypically inherited from its parent scope
Therefore,any changes made to this scope will not get reflected back to the parent scope. However any changes made in the EgController ( the parent scope) will get reflected in the directive scope.
3. Isolated scope :
In this scope, both directive and controller have their own scope. And data can be passed to the directive as:
- a string using @ string literal
- an object using = string literal
- a function
Here is an example:
App.directive(Eg, function () {
return {
restrict: 'E',
scope: {
name: '@',
},
template: '
{{name}} '
};
});
as an object
App.directive(Eg, function () {
return {
restrict: 'E',
scope: {
data: '='
},
template: '
{{data.name}}
'
};
});
as a function
App.directive(Eg, function () {
return {
restrict: 'E',
scope: {
data: '&',
},
template: '
{{data.name}}
'
};
});
0 Comment(s)