AngularJS指令:在同一页面中多次显示

时间:2015-07-08 14:35:01

标签: angularjs angularjs-directive

我有一个包含大量数据的数组。 我需要在同一页面的不同区域(大约10次)显示它(使用不同的过滤)。

为了防止长时间加载(多次'ng-repeat'),我试图将它放在一个指令中并多次显示相同的指令(而不是'ng-repeat')。

我希望指令在每次都是同一个实例时显示,而不是创建新对象(以这种方式加速加载)。 如何让指令显示相同的实例,而不是一遍又一遍地创建自己?

我的示例代码:

Plunker

var contec = angular.module('app', [])

 .controller('MainCtrl', function($scope,$rootScope) {

   $scope.change = function(){
     var id = Math.floor((Math.random() * 4) + 0);
     var val = Math.floor((Math.random() * 100) + 1);
     $rootScope.data.items[id].id = val;
  }

 $rootScope.data = {
   items: [{
     id: 1,
     name: "first"
    }, {
     id: 2,
     name: "second"
    }, {
     id: 3,
     name: "third"
    }, {
     id: 4,
     name: "forth"
  }]
}
});

contec.directive('firstDirective', function($rootScope,$compile) {
return {

replace: true,
restrict: 'EA',
scope: {
  data: '='
},
link: function(scope, element, attrs) {

  var template = '';
        angular.forEach($rootScope.data.items, function(item, key) {
          var tmp = '<div second-directive data="' + key + '"></div>';

            template = template + tmp; 
         });

          element.html(template);
          $compile(element.contents())(scope);
   }
   }
  });

contec.directive('secondDirective', function($rootScope,$compile) {
  var comp = function(scope,element, attrs,firstDirective){

  var index = scope.data;
  scope.item = $rootScope.data.items[index];


  var template = '<ng-include src="\'itemTemplate.html\'"></ng-include>';
    element.html(template);

    $compile(element.contents())(scope);
 }

return {
   restrict: 'EA',
   link: comp,
   scope: {
        data: '='
   },
 };
 });

1 个答案:

答案 0 :(得分:0)

我认为使数据实例可用的最佳方法是将其包装在服务(特别是工厂)中

例如:

contec.factory('DataFactory', function() {
    var data = {
        items: [{
            id: 1,
            name: "first"
        }, {
            id: 2,
            name: "second"
        }, {
            id: 3,
            name: "third"
        }, {
            id: 4,
            name: "forth"
        }]
    }

    return {
        getData(): function() {
            return data;
        }
    }
}

然后,您将能够在任何需要它的控制器中注入工厂。

contec.controller('ExampleController', ['DataFactory', ExampleController]);

function ExampleController(DataFactory) {
    this.data = DataFactory.getData();
}

这种方法具有更易测试的额外好处,因为您可以轻松地在单元测试中注入模拟数据。