问题
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.
回答1:
Here is a plunker: http://plnkr.co/edit/bNjSnee5UwVjp6wHE6RK
I created a directive:
- I use
$parse
rather than$eval
for optimizations. - You provide a collection to watch and an expression to run on each change.
- It works like
ngInit
only it updates when the collection is dirty. - I chose general names for attributes, you can change it to what you like.
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">
回答2:
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>
来源:https://stackoverflow.com/questions/21408274/angularjs-binding-a-variable-in-template-to-increase-performances