【发布时间】:2015-07-08 14:35:01
【问题描述】:
我有一个包含大量数据的数组。 我需要在同一页面的不同区域(大约 10 次)显示它(使用不同的过滤)。
为了防止加载时间过长(多个“ng-repeat”),我试图将它放在一个指令中并多次显示相同的指令(而不是“ng-repeat”)。
我希望指令在每次都是同一个实例时显示,而不是创建新对象(并以这种方式加快加载速度)。 我怎样才能让指令显示相同的实例而不是一遍又一遍地创建自己?
我的示例代码:
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