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)?
Expressions in AngularJS are used to bind application data to HTML. The expressions are resolved by AngularJS and the result is returned back to where the expression is written. The expressions in AngularJS are written in double braces: {{ expression }}. They behave similar to ng-bind directives: ng-bind=”expression”.
AngularJS expressions can be written inside double braces: {{ expression }} . AngularJS expressions can also be written inside a directive: ng-bind="expression" . AngularJS will resolve the expression, and return the result exactly where the expression is written.
The $ in AngularJs is a built-in object.It contains application data and methods.
It means it's used to achieve one time binding. Example. angular.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With