AngularJS:模板绑定变量来提高性能 [英] AngularJS : Binding a variable in template to increase performances
本文介绍了AngularJS:模板绑定变量来提高性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我用一个code样品:</ P>
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>
正如你所见,我需要过滤我的'元素的数组3倍。我想用这种下code键增强perfs的:
的(这只是我所需要的,不是真正的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>
我试图用NG-INIT'属性来处理它。它的工作很大...但我的模型变化,而不是更新的值时
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.
推荐答案
下面是一个plunker:的http:// plnkr .CO /编辑/ bNjSnee5UwVjp6wHE6RK
Here is a plunker: http://plnkr.co/edit/bNjSnee5UwVjp6wHE6RK
- 我用
$解析
,而不是$ EVAL
的优化。 - 您提供一个集观赏与前任pression在每次改变运行。
- 它像
ngInit
仅在更新时在集是脏的。 - 我选择了通用名称的属性,你可以把它改成你喜欢什么。
- 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.
指令
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">
这篇关于AngularJS:模板绑定变量来提高性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文