我有一些数据被称为foo生活在三个孩子的父母的范围内:
<div ng-init="foo=[1, 2, 3]">
<bar foo="{{foo}}" baz="{{odp}}" />
<mpq foo="{{foo}}" bats="{{maktz}}" />
<ktr foo="{{foo}}" otr="{{ompg}}" />
</div>
bar.scope = {foo: '=', baz: '@'};
mpq.scope = {foo: '=', bats: '@'};
ktr.scope = {foo: '=', otr: '@'};
Run Code Online (Sandbox Code Playgroud)
foo在这三个指令之间分享的最佳方式是什么?选项包括:
foo三次,从而在四个范围内复制它baz,bats或otr在attrsfoo它$rootScope注入并注入子指令或者还有另一种方法更好吗?
Ben*_*esh 27
您可以创建一个可以传递给每个指令或控制器的工厂.这将确保您在任何给定时间只有一个数组实例.编辑:这里唯一的问题是确保你在指令范围内设置引用类型而不是原始类型,或者你最终会复制每个范围中的值.
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: [] };
}]);
Run Code Online (Sandbox Code Playgroud)
HTML
<dir1></dir1>
<dir2></dir2>
<dir3></dir3>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29725 次 |
| 最近记录: |