13

Is there any reason you would choose one technique over another?

 var items = [{val:7},{val:3},{val:4},{val:1}];

First: Ctrl and View

 $scope.doSomething = function(val){
     return val + 10;
 };

 <div ng-repeat="item in items">
     {{ doSomething(item.val) }}
 </div>

Second: Ctrl and View

 angular.forEach(items,function(item){
      item.val = item.val + 10;
      //item.valAlso = item.val + 10; Or in case you want to preserve model
 });

 <div ng-repeat="item in items">
     {{ item.val }}
 </div>

I usually prefer the second technique (for instance after an http request), but I am wondering if and why specifically one is superior to the other. I know the first technique could end up calling $scope.doSomething multiple times on each digest cycle (for each item in the repeater), but I have heard the argument this is not all that much different from using a filter. Any ideas?

Edit: I am most specifically wondering about the effects on dirty checking, the digest cycle, scope watches etc. Also is function complexity relevant at all (imagine a much more complex function)?

2
  • @Chandermani could you elaborate on your answer? Commented Feb 28, 2014 at 4:09
  • My bad i was thinking something else :( Nevermind Commented Feb 28, 2014 at 5:54

1 Answer 1

6

There will be no performance difference in either, but in terms of semantics and clean separation, there is no reason ever to use the first method. That's what filters were designed and optimized for.

The complexity of the function won't differ between one method to the other as the dirty checks happen in exactly the same way.

If you are modifying the value of the items, then your logic for that should definitely be kept out of your view, i.e. the second example.

Sign up to request clarification or add additional context in comments.

2 Comments

If you place a console.log inside the function doSomething, it can be called multiple times per digest for each list item. However the forEach loop only runs once (on instantiation or a server request). Isn't there something fundamentally different about these techniques?
Both techniques have their place and what matters is why the value is being changed. If the view is saying "If you had 10 more potatoes you would have...", it would be wrong to adjust the current number of potatoes in the controller or model for display purposes because that would make the value incorrect. Creating a new property called future potatoes would be fine or adjusting the value at the point of display. However, if the value received at the backend needs to be adjusted to correctly reflect its meaning, it should be adjusted there and not in the view.

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.