问题
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?
回答1:
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;
}
});
来源:https://stackoverflow.com/questions/33769644/angular-ng-repeat-data-binding-function-performance