javascript 表达式中的 AngularJs 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22083885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:24:34  来源:igfitidea点击:

AngularJs functions in expressions

javascriptangularjs

提问by TheBigC

Is there any reason you would choose one technique over another?

您有什么理由选择一种技术而不是另一种技术?

 var items = [{val:7},{val:3},{val:4},{val:1}];

First: Ctrl and View

第一:Ctrl 和 View

 $scope.doSomething = function(val){
     return val + 10;
 };

 <div ng-repeat="item in items">
     {{ doSomething(item.val) }}
 </div>

Second: Ctrl and View

第二:Ctrl 和 View

 angular.forEach(items,function(item){
      item.val = item.val + 10;
      //item.valAlso = item.val + 10; Or in case you want to preserve model
 });

 <div ng-repeat="item in items">
     {{ item.val }}
 </div>

I usually prefer the second technique (for instance after an http request), but I am wondering if and why specifically one is superior to the other. I know the first technique could end up calling $scope.doSomething multiple times on each digest cycle (for each item in the repeater), but I have heard the argument this is not all that much different from using a filter. Any ideas?

我通常更喜欢第二种技术(例如在 http 请求之后),但我想知道是否以及为什么特别优于另一种。我知道第一种技术最终可能会在每个摘要循环中多次调用 $scope.doSomething(对于转发器中的每个项目),但我听说这与使用过滤器并没有太大不同的论点。有任何想法吗?

Edit: I am most specifically wondering about the effects on dirty checking, the digest cycle, scope watches etc. Also is function complexity relevant at all (imagine a much more complex function)?

编辑:我最特别想知道对脏检查、摘要周期、范围监视等的影响。还有函数复杂性是否相关(想象一个更复杂的函数)?

回答by Dan Prince

There will be no performance difference in either, but in terms of semantics and clean separation, there is no reason ever to use the first method. That's what filters were designed and optimized for.

两者都没有性能差异,但在语义和干净分离方面,没有理由使用第一种方法。这就是过滤器的设计和优化目的。

The complexity of the function won't differ between one method to the other as the dirty checks happen in exactly the same way.

由于脏检查以完全相同的方式发生,因此函数的复杂性在一种方法与另一种方法之间不会有所不同。

If you are modifying the value of the items, then your logic for that should definitely be kept out of your view, i.e. the second example.

如果您正在修改项目的值,那么您的逻辑绝对应该保持在您的视野之外,即第二个示例。