Reputation: 1049
I'm new to AngularJS and trying to create my first custom directives.
Actually I created two directives each using it's own controller. Maybe I got it wrong but I expected that each directive controller uses it's own isolated $scope. But within the template of 'Directive One' I can call a variable from 'Directive Two' and vice versa.
How can I get a isolated $scope for each directive so that each directive's template can only use it's own variables?
index.html:
<!DOCTYPE html>
<html ng-app="application">
<head>
<script src="https://code.angularjs.org/1.2.28/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Testing Custom Directives</h1>
<hr />
<directive-one></directive-one>
<directive-two></directive-two>
</body>
</html>
script.js:
var app = angular.module('application', [ ]);
app.directive('directiveOne', function(){
return {
restrict: 'E',
template: '<h3>Directive 1</h3> {{dirCtrlOne.name}} {{dirCtrlTwo.year}}',
controller:function(){
this.name = 'John';
},
controllerAs: 'dirCtrlOne'
}
});
app.directive('directiveTwo', function(){
return {
restrict: 'E',
template: '<h3>Directive 2</h3> {{dirCtrlTwo.year}} {{dirCtrlOne.name}}',
controller:function(){
this.year = 1990;
},
controllerAs: 'dirCtrlTwo'
}
});
Upvotes: 1
Views: 96
Reputation: 3303
Write scope: {}
in your directive that isolates the directive’s scope from any parent scope(s)
As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in.
Upvotes: 0
Reputation: 923
By default a directive inherits the scope of it parent and by adding variables to the scope of the directive adds that to the parent as well. This is the reason why both your directives have access to the other ones variables. In order to have the scopes isolated please try this code:
var app = angular.module('application', [ ]);
app.directive('directiveOne', function(){
return {
restrict: 'E',
scope: true,
template: '<h3>Directive 1</h3> {{dirCtrlOne.name}} {{dirCtrlTwo.year}}',
controller:function(){
this.name = 'John';
},
controllerAs: 'dirCtrlOne'
}
});
app.directive('directiveTwo', function(){
return {
restrict: 'E',
scope: true,
template: '<h3>Directive 2</h3> {{dirCtrlTwo.year}} {{dirCtrlOne.name}}',
controller:function(){
this.year = 1990;
},
controllerAs: 'dirCtrlTwo'
}
});
Upvotes: 1