指令之间的数据共享 [英] Sharing data between directives
问题描述
我有一些数据名为富
它生活在一个范围是父母三个孩子:
I have some data called foo
which lives in a scope which is parent to three children:
<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: '@'};
什么是分享富
这三个指令之间的最佳方式?选项包括:
What is the best way to share foo
between those three directives? Options include:
- 使用一个孤立的范围,
富
三次传递,从而复制它在四个范围 - 让孩子指示继承父范围,并找到
巴兹
,蝙蝠
或OTR
在ATTRS
- 把
富
在$ rootScope
并注入了进入孩子的指令
- Use an isolated scope to pass in
foo
three times, thereby duplicating it across four scopes - Have the child directives inherit the parent scope, and find
baz
,bats
, orotr
onattrs
- Put
foo
on the$rootScope
and inject that into the child directives
还是有另一种方法更好?
Or is there another approach that is better?
推荐答案
您可以创建一个可以传递给每一个指令或控制器的服务。这将确保你只有数组的一个实例在任何给定的时间。编辑:这里唯一的疑难杂症是确保你设置你的指令范围引用类型,而不是原始类型,或者你最终会在每个范围中重复的值
You can create a service that you can pass to each directive or controller. That will make sure you only have one instance of the array at any given time. The only gotcha here is to make sure you're setting reference types and not primitive types on your directive scopes, or you'll end up duplicating the values in each scope.
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>
这篇关于指令之间的数据共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!