我有以下Angular Directive,它从父控制器的范围获取数据。我的问题是,当同一指令多次添加到同一页面时,它们的范围变得相同。只要更改了任何指令中的某个值,所有指令中的相同值也会发生变化。
我的指示
angular.module('myapp').directive('memberAddress', function () {
return {
restrict: 'E',
templateUrl: '/Directives/memberAddress.html'
}
});
memberAddress.html:
<div class="col-md-4">
<h3>{{addressModel.title}}</h3>
</div>
家长设计:
<div id="addressDiv">
<div class="row"></div>
</div>
家长控制器:
angular.module('myapp').controller('MemberController', MemberController);
MemberController.$inject = ['$scope', '$compile'];
function MemberController($scope, $compile) {
$scope.addressModel = { title: ''}
$scope.addAddress = function () {
// "$scope.addressModel" Now it has some title text from UI.
var row = angular.element(document.getElementById('addressDiv')).find('.row');
var el = $compile("<member-address></member-address>")($scope);
row.append(el);
}
}
在调用addAddress()时,它会添加一个&#34; memberAddress&#34;指令第一次到页面。但是当我从UI添加另一个addressModel.title时,它会添加一个新的指令,但它会更改之前添加的&#34; memberAddress&#34;指令,使所有指令的标题文本相同。
有没有办法阻止其他指令改变?
答案 0 :(得分:0)
在指令中设置范围,而不是在控制器中。角度js网站有一个例子。
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: { customerInfo: '=info' },
templateUrl: 'my-customer-iso.html'
};
});
要使其与您的代码一起使用,您可能还必须将控制器重写为您的指令。
代码学校在他们的'塑造角度'
指令章节中非常清楚地说明了这一点答案 1 :(得分:0)
尝试使用隔离范围:
angular.module('myapp').directive('memberAddress', function () {
return {
scope: {
addressModel: "@"
},
restrict: 'E',
templateUrl: '/Directives/memberAddress.html'
}
});
memberAddress.html:
<div class="col-md-4">
<h3>{{addressModel().title}}</h3>
</div>
家长设计:
<div id="addressDiv">
<div class="row">
<member-address address-model="addressModel"></member-address>
</div>
</div>
答案 2 :(得分:0)
我通过为每个指令声明新范围来解决它。
以下是父控制器中的更改:
angular.module('myapp').controller('MemberController', MemberController);
MemberController.$inject = ['$scope', '$compile'];
function MemberController($scope, $compile) {
$scope.addressModel = { title: ''}
$scope.addAddress = function () {
// "$scope.addressModel" Now it has some title text from UI.
// UPDATE - Here I created a new scope.
var addressDirectiveScope = $scope.$new(true);
addressDirectiveScope.addressModel = $scope.addressModel;
var row = angular.element(document.getElementById('addressDiv')).find('.row');
//var el = $compile("<member-address></member-address>")($scope);
// UPDATE - Now I passed the new scope "addressDirectiveScope" instead of "$scope" to $compile.
var el = $compile("<member-address></member-address>")(addressDirectiveScope);
row.append(el);
}
}
感谢大家的回答!