为什么angularjs会调用函数`name()`两次?

前端之家收集整理的这篇文章主要介绍了为什么angularjs会调用函数`name()`两次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
代码很简单:
  1. <!doctype html>
  2. <html ng-app="plunker" >
  3. <head>
  4. <Meta charset="utf-8">
  5. <title>AngularJS Plunker</title>
  6. <script>document.write("<base href=\"" + document.location + "\" />");</script>
  7. <link rel="stylesheet" href="style.css">
  8. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script>
  9. </head>
  10. <body ng-controller="MainCtrl">
  11. Hello {{name()}}!
  12. </body>
  13. </html>
  14. <script>
  15. var app = angular.module('plunker',[]);
  16.  
  17. app.controller('MainCtrl',function($scope) {
  18. $scope.name= function() {
  19. console.log("---name---:" + new Date());
  20. return "Freewind";
  21. };
  22. });
  23.  
  24. </script>

你可以看到有一个名字函数,我们只在一次调用它在正文中。但在控制台中,它打印两次—名称— ::

  1. ---name---:Wed Feb 20 2013 14:38:12 GMT+0800 (中国标准时间)
  2. ---name---:Wed Feb 20 2013 14:38:12 GMT+0800 (中国标准时间)

你可以在这里看到一个现场演示:http://plnkr.co/edit/tb8RpnBJZaJ73V73QISC?p=preview

为什么函数name()被调用了两次?

在AngularJS中,包裹在双花括号中的任何东西都是 expression,在摘要循环中至少进行一次评估。

AngularJS通过连续运行摘要循环,直到没有变化。这就是它确保视图是最新的。既然你调用了一个函数,它运行一次来​​获取一个值,然后再次看到没有改变。在下一个摘要循环中,它将至少运行一次。

由于这个原因,通常只能从模板中调用幂等方法(如名称)。

猜你在找的Angularjs相关文章