0

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?

2
  • Will startTime and duration change once the width has been calculated once? If not you could use one time bindings or simply precalculate it. Commented Nov 18, 2015 at 4:59
  • Yes they can change but only on page refresh with a new object returned. I will give this a try Commented Nov 18, 2015 at 17:01

1 Answer 1

2

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;
 }
});
Sign up to request clarification or add additional context in comments.

2 Comments

For option 2, when you say item directive, do you mean create another directive that goes on the div style. If so, could adding the style changes to the compile phase/ pre-linking phase be the best approach?
@Garuuk I've added an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.