Reputation: 1870
Here is a code sample I use:
<div ng-class="{alert: ((elements|filter:{hasAlert: true}).length / elements.length) > maxPercentAlerts}">
{{(elements|filter:{hasAlert: true}).length}}
({{Math.floor((elements|filter:{hasAlert: true}).length * 100 / elements.length)}} %)
</div>
As you see, I need to filter my 'elements' array 3 times. I would like to use this kind of following code to increase perfs: (this is just an example of what I need, not real code)
<div some-ng-prop="alertCount=(elements|filter:{hasAlert: true}).length"
<div ng-class="{alert: (alertCount / elements.length) > maxPercentAlerts}">
{{alertCount}}
({{Math.floor(alertCount * 100 / elements.length)}} %)
</div>
I've tried to handle it with the 'ng-init' attribute: it worked great... But when my model changes, the values are not updated.
Is there a way to do that ?
I've tried to be clear, but please ask for details if you don't understand what I mean.
Upvotes: 1
Views: 1201
Reputation: 32377
Here is a plunker: http://plnkr.co/edit/bNjSnee5UwVjp6wHE6RK
$parse
rather than $eval
for optimizations.ngInit
only it updates when the collection is dirty.directive:
app.directive('watchCollection', function($parse){
return {
compile: function(tElm,tAttrs){
if(! tAttrs.assign) return;
var assignFn = $parse(tAttrs.assign)
return function(scope,elm,attrs){
scope.$watchCollection(tAttrs.watchCollection , function(val){
assignFn(scope);
})
}
}
}
})
html:
<div watch-collection="elements"
assign="alertCount=(elements|filter:{hasAlert: true}).length">
Upvotes: 1
Reputation: 1870
Stewie suggested it was a duplicate, I think it's not but it made me try the following code which works great :
<div ng-class="{alert: (alertCount / elements.length) > maxPercentAlerts}">
{{alertCount = (elements|filter:{hasAlert: true}).length}}
({{Math.floor(alertCount * 100 / elements.length)}} %)
</div>
Upvotes: 0