AngularJS:`{{x +','+ y}}`与`{{x}},{{y}}`

时间:2016-04-15 14:42:35

标签: angularjs

{{ x + ', ' + y }}{{ x }}, {{ y }}有什么影响吗?

特别是在观察者的成本方面?

我想知道我是否可以通过组合双向绑定花括号来减少摘要循环的数量。

提前致谢。

3 个答案:

答案 0 :(得分:2)

One digest loop would handle one or both of them if it's going to do it at all; it won't be a digest for x and then another for y (unless you trigger a new one later). Technically, I'd say the former one is slightly more taxing because it involves string concatenation, but I suspect this has to happen at some point behind the scenes with the latter version anyway.

Overall, I don't expect you'll get a noticeable performance difference with this level of expression unless you're displaying hundreds or thousands of them at once (in which case, you'll probably have other problems as well and should rethink your approach).

答案 1 :(得分:2)

The {{}} notation is slower than using the ng-bind directive :

The {{}} will be dirty checked at every digest cycle whereas ng-bind places a watcher on the value passed in parameter and will update it only when it has changed. Another advantage of using ng-bind over {{}} is that the user won't see the {{}} in the page when angular is still loading.

Additionally you can use the new :: notation (introduced in angular 1.3) for static binding (when you know your variable won't change) :

<h1 data-ng-bind="::title"></h1>

About the references for the {{}} vs ng-bind notations :

"ng-bind is faster because it’s simpler. interpolation has to go through extra steps of verifying context, jsonification of values and more. that makes it slightly slower."

答案 2 :(得分:1)

TO be precise the first expression will produces one watch but angular will recompute the concatenation.

On the second line you may think there will be 2 watch but it may be not (i'm not sure). I know that if you do this :

<span> blabla {{x}} blabla</span>

Angular will watch the whole content of the span. So if you have multiple usage of brackets you will very likely have only one watch for the whole thing.