加快角$编译功能 [英] Speeding up Angular $compile function
问题描述
我手动编译模板对一个新的范围:
I'm manually compiling a template against a new scope:
var scope = _.assign($rootScope.$new(true), {
foo: 1,
bar: 2
})
var element = angular.element('<my-element foo="foo" bar="bar"></my-element>')
$compile(element)(scope)
element.appendTo(container)
运行的基本轮廓,这code最慢的部分后为 $编译
,其中每个编译需要1毫秒〜。我需要一次编译〜100元,当用户滚动。
After running a basic profile, the slowest part of this code is $compile
, which takes ~1ms per compilation. I need to compile ~100 elements at a time, as the user scrolls.
有很多优化工作,我可以申请加快编译第一轮的$编译之后,但我想,以加快非常第一轮100编译的。我也想保持Angularland模板,避免注入原始的HTML。
There are a lot of optimizations I can apply to speed up compilations after the 1st round of $compiles, but I'd like to speed up the very 1st round of 100 compiles. I'd also like to keep the templates in Angularland, and avoid injecting raw HTML.
如何?
编辑:复制粘贴+从下面这里能见度任何人看到这个线程在未来我的评论:
Copy+pasting my comment from below here for visibility for anyone that sees this thread in the future:
好吧,这总算是有道理的。如果你在一个函数作为第二个参数$环节传递,角会克隆你的节点。如果你不这样做,它会重用每次调用$连接同一个节点。无论哪种方式,您可以访问返回的节点都同步(如$链接的返回值)和异步(回调之内)。这是一个设计不当的API,我在角的问题跟踪器提交一个问题在这里 - github.com/angular/angular.js/issues/11824
Ok, it finally makes sense. If you pass in a function as a 2nd argument to $link, angular will clone the node for you. If you don't, it will reuse the same node on every call to $link. Either way, you can access the returned node both synchronously (as the return value of $link) and asynchronously (within your callback). This is a poorly designed API, I filed an issue in Angular's issue tracker here - github.com/angular/angular.js/issues/11824
推荐答案
如果元素都是相同的结构,而且仅针对它们所连接的范围不同,那么你应该 $编译
模板的一次的再链接
对每一个相应范围的100个元素。
If the elements are of the same structure and only differ in the scope against which they are linked, then you should $compile
the template once and then link
each of the 100 elements against their respective scopes.
var myElement = angular.element('<my-element foo="foo" bar="bar"></my-element>');
var myElementLinkFn = $compile(myElement);
// "items" here is the data that drives the creation of myElement elements
angular.forEach(items, function(item){
var newScope = $scope.$new(true);
newScope.foo = item.foo;
newScope.bar = item.bar;
myElementLinkFn(newScope, function(clone){
container.append(clone);
})
});
这篇关于加快角$编译功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!