小编典典

在指令之间共享数据

angularjs

我有一些称为的数据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: '@'};

foo在这三个指令之间共享的最佳方法是什么?选项包括:

  • 使用隔离的范围传递foo三遍,从而跨四个范围复制它
  • 让子指示继承父范围,并找到bazbatsotrattrs
  • foo$rootScope并注入到这一点的子指示

还是有另一种更好的方法?


阅读 370

收藏
2020-07-04

共1个答案

小编典典

您可以创建一个工厂,该工厂可以传递给每个指令或控制器。这样可以确保在任何给定时间只有一个数组实例。编辑:这里唯一的陷阱是确保您在指令作用域上设置引用类型,而不是原始类型,否则最终将在每个作用域中复制值。

这是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>
2020-07-04