【问题标题】:AngularJS Directive: display multiple times in the same pageAngularJS指令:在同一页面中多次显示
【发布时间】:2015-07-08 14:35:01
【问题描述】:

我有一个包含大量数据的数组。 我需要在同一页面的不同区域(大约 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: '='
   },
 };
 });

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    我认为让你的数据实例可用的最好方法是将它包装在一个服务中(特别是一个工厂)

    例如:

    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();
    }
    

    这种方法的另一个好处是更易于测试,因为您可以轻松地在单元测试中注入模拟数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-21
      • 2021-06-12
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多