What is the difference between scope:{} and scope:true inside directive?
Both scope: true
and scope:{}
will create a child scope for the directive. But,
scope:true
will prototypically inherit the properties from the parent(say the controller where the directive comes under) where as scope:{}
will not inherit the properties from the parent and hence called isolated
For instance lets say we have a controller c1 and two directives d1 and d2,
app.controller('c1', function($scope){
$scope.prop = "some value";
});
.directive('d1', function() {
return {
scope: true
};
});
.directive('d2', function() {
return {
scope: {}
};
});
<div ng-controller="c1">
<d1><d1>
<d2><d2>
</div>
d1(scope:true) will have access to c1 scope -> prop where as d2 is isolated from the c1 scope.
Note 1: Both d1 and d2 will create a new scope for each directive defined.
Note 2: Apart from the difference between the two, for scope:true
- Any changes made to the new child scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the c1 scope(the parent scope) will be reflected in the directive scope.
Tip: Use scope:{}
or isolated scope
for reusable angular directives. So that you won't end up messing with the parent scope properties
scope : true
Angular JS will create a new scope by inheriting parent scope ( usually controller scope, else application’s root Scope ).
Note : Any changes made to this new scope will not reflect back to the parent scope. However, since the new scope is inherited from the parent scope, any changes made in the parent scope i.e. controller will be reflected in the directive scope.
scope : false
The controller and directive are using the same scope object. This means any changes to the controller or directive will be in sync.
scope : {}
New scope created for the directive, but it will not be inherited from the parent scope. This new scope also known as Isolated scope because it is completely detached from its parent scope.
scope: true creates a new scope for the directive that inherits everything from the parents
scope : {} also creates a new scope for the directive, but it's isolated, so it doesn't inherit anything from the parents
Take a look a this article:
http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/