您可以创建一个可以传递给每个指令或控制器的工厂。这将确保您在任何给定时间都只有一个数组实例。编辑:这里唯一的问题是确保您在指令范围内设置引用类型而不是原始类型,否则您最终将复制每个范围中的值。
这是 Plnkr.co 上的一个示例
app.controller('MainCtrl', function($scope, dataService) {
$scope.name = 'World';
//set up the items.
angular.copy([ { name: 'test'} , { name: 'foo' } ], dataService.items);
});
app.directive('dir1', function(dataService){
return {
restrict: 'E',
template: '<h3>Directive 1</h3>' +
'<div ng-repeat="item in data.items">' +
'<input type="text" ng-model="item.name"/>' +
'</div>',
link: function(scope, elem, attr) {
scope.data = dataService;
}
};
});
app.directive('dir2', function(dataService){
return {
restrict: 'E',
template: '<h3>Directive 2</h3>' +
'<div ng-repeat="item in data.items">' +
'<input type="text" ng-model="item.name"/>' +
'</div>',
link: function(scope, elem, attr) {
scope.data = dataService;
}
};
});
app.directive('dir3', function(dataService){
return {
restrict: 'E',
template: '<h3>Directive 3</h3>' +
'<div ng-repeat="item in data.items">' +
'<input type="text" ng-model="item.name"/>' +
'</div>',
link: function(scope, elem, attr) {
scope.data = dataService;
}
};
});
app.factory('dataService', [function(){
return { items: [] };
}]);
HTML
<dir1></dir1>
<dir2></dir2>
<dir3></dir3>