Multiple Instance Of Same Angular Directive Mess Up Scope Variables
I am using the directive multiple times on the page like My directive looks like When this code renders it gives call to backend service to populate sources based on the search k
Solution 1:
scope
is prototypically inherited in Angular, but a new scope is only created if you request it. In this case, you are simply decorating the existing scope defined by the parent that your directive is sitting in.
This means that anything added to scope will be overwritten by the same directive.
You can tell your directive to create a new scope by simply adding the scope:true
property to your directive definition object:
{
restrict : 'A',
scope:true
//more stuff
}
Here is a simple example to show the difference between a directive that creates a new scope, and one that does not.
(function() {
'use strict';
functionNoNewScope() {
return {
restrict: 'A',
template: [
'<div class="form-group">',
' <label>Name - <code>{{name}}</code></label>',
' <input class="form-control" type="text" ng-model="name" />',
'</div>'
].join(''),
link: function(scope) {
scope.name = "No New Scope";
}
};
}
functionNewScope() {
return {
restrict: 'A',
scope: true,
template: [
'<div class="form-group">',
' <label>Name - <code>{{name}}</code></label>',
' <input class="form-control" type="text" ng-model="name" />',
'</div>'
].join(''),
link: function(scope) {
scope.name = "New Scope";
}
};
}
angular.module('my-app', [])
.directive('noNewScope', NoNewScope)
.directive('newScope', NewScope);
}());
<linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /><scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script><divng-app="my-app"class="container"><divclass="row"><divclass="col-xs-6"><h3>NO new scope</h3><divno-new-scope></div><divno-new-scope></div></div><divclass="col-xs-6"><h3>NEW scope</h3><divnew-scope></div><divnew-scope></div></div></div></div>
Post a Comment for "Multiple Instance Of Same Angular Directive Mess Up Scope Variables"