Sharing data between directives

前端 未结 1 1697
暖寄归人
暖寄归人 2020-11-29 04:23

I have some data called foo which lives in a scope which is parent to three children:

相关标签:
1条回答
  • 2020-11-29 04:49

    You can create a factory 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. EDIT: 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.

    Here is an example on 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>
    
    0 讨论(0)
提交回复
热议问题