angular ng-repeat 数据绑定功能性能 [英] angular ng-repeat data binding function performance
问题描述
我正在遍历大量数据.每个对象都有一个属性 startTime 和 duration,对于每个对象都是唯一的.
我需要计算数组中每个对象的 startTime 和持续时间,并根据这些计算设置元素宽度.
<div style="width:{{calculateWidth(event.startTime, event.duration)}}%"><div>更多内容</div><div>
和我的 js
$scope.calculateWidth = function(duration, starTime){var secondsInDay = 86400;var width = (duration/secondsInDay)*100;返回宽度;}
出于示例目的,我简化了我的代码,并且省略了更多计算.总体而言,这对于少于 30 个对象可以正常工作,但随着数据的增长,性能会有所下降.
在 Angular 中有更好的方法吗?
我看到 2 个选项:
- 加载数据时预先计算样式值并通过 ng-style 进行设置
- 创建另一个item"指令,用于最初计算和应用样式,并在需要时设置观察者
我会选择 2,涉及最少的表达.
像这样:
<div my-event="event"><div>更多内容</div><div>
和指令本身:
module.directive('myEvent', function() {返回 {范围:{事件:=我的事件"},链接:链接}功能链接(范围,元素,属性){var event = scope.event;element.style.width = calcWidth(event.startTime, event.duration)+'px';}函数calcWidth(持续时间,starTime){var secondsInDay = 86400;var width = (duration/secondsInDay)*100;返回宽度;}});
I'm looping through lots of data. Each object has a property startTime and duration, which is unique for each object.
I need to do calculations on this startTime and duration for each object in the array and set the elements width based off these calculations.
<div ng-repeat = "event in events track by event.id">
<div style="width:{{calculateWidth(event.startTime, event.duration)}}%">
<div>more content</div>
</div>
<div>
and my js
$scope.calculateWidth = function(duration, starTime){
var secondsInDay = 86400;
var width = (duration / secondsInDay)*100;
return width;
}
I simplified my code for example purpose and there are more calculations I omitted. Overall, This works fine for less than 30 objects but performance lacks as the data grows.
Is there a better way to do this in Angular?
I see 2 options:
- pre-compute styles values when data is loaded and set it via ng-style
- create another 'item' directive that would calculate and apply styles initially and setup watchers if needed
I'd go for number 2, least amount of expressions involved.
edit: Something like this:
<div ng-repeat = "event in events track by event.id">
<div my-event="event">
<div>more content</div>
</div>
<div>
and directive itself:
module.directive('myEvent', function() {
return {
scope:{
event:"=myEvent"
},
link:link
}
function link (scope,element, attrs){
var event = scope.event;
element.style.width = calcWidth(event.startTime, event.duration)+'px';
}
function calcWidth(duration, starTime){
var secondsInDay = 86400;
var width = (duration / secondsInDay)*100;
return width;
}
});
这篇关于angular ng-repeat 数据绑定功能性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!