问题
In first case: I implemented a directive directive2
that will change bar
value which will also get reflected in directive1
.
Here u can find the plunkr (1st case)
In second case:I implemented a directive directive2
, with ng-repeat
used along with this directive that changes bar
value and this is supposed to get reflected in directive1
.
Here u can find the plunkr for directive2
with ng-repeat
(2nd case)
How i expect it to work: i want the bar
in directive1
to change according to the change in directive2
My question: 1st case is working the way i want. In the 2nd case my bar
value in directive1
is not changing according to changes made in directive2
.
My assumption is that using ng-repeat
is creating multiple scopes and hence not working the way i want.
How do i solve this?
HTML snippet(2nd case)
<body ng-controller="MainCtrl">
this is directive1: <directive1></directive1>
<br />
<div ng-repeat="item in [1,2]">
this is directive2 for ng-repeat {{item}}
<directive2 bar="bar"></directive2>
</div>
</body>
JS snippet(2nd case)
var app = angular.module('myApp', []);
app.directive('directive1', function() {
return {
restrict: 'E',
replace: true,
template: '<div><span>{{bar}}</span></div>'
}
});
app.directive('directive2', function() {
return {
restrict: 'E',
scope:{
bar:"="
},
replace: true,
link:function(s,e,a){
s.bar = "Changed value";
},
template: '<div><b>{{bar}}</b></div>'
}
});
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.bar ="original value";
});
回答1:
You have correctly guessed it! This is happening because of child scopes created by ng-repeat
.
When you are creating a isolated scope with bar
dependency the set operation on bar
is setting the bar value on parent scope. In case of ng-repeat the parent scope is the ng-repeat
scope and hence this behaviour.
Use a object instead of string to pass the string reference around and it will work. Check my plunkr http://plnkr.co/edit/JCQsIXzRv9FUNfJwhOAB?p=preview
Set bar variable as
$scope.data={};
$scope.data.bar ="original value";
User directive like
<directive2 bar="data.bar"></directive2>
来源:https://stackoverflow.com/questions/29874648/angularjs-how-to-reflect-a-variable-change-in-one-directive-into-another-direc