指令之间的数据共享 [英] Sharing data between directives

查看:164
本文介绍了指令之间的数据共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些数据名为它生活在一个范围是父母三个孩子:

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, or otr on attrs
  • 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.

这里是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>

这篇关于指令之间的数据共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆