本文介绍了为什么angularjs将调用函数'名称()`两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在code是简单的:

<!doctype html>
<html ng-app="plunker" >
<head>
  <meta charset="utf-8">
  <title>AngularJS Plunker</title>
  <script>document.write("<base href=\"" + document.location + "\" />");</script>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script>
</head>
<body ng-controller="MainCtrl">
  Hello {{name()}}!
</body>
</html>
<script>
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name= function() {
    console.log("---name---:" + new Date());
    return "Freewind";
  };
});

</script>

您可以看到有一个名称函数,我们调用它在体内只有一次。但在控制台,它打印的两倍 ---名字---

You can see there is a name function and we invoke it in the body only one time. But in the console, it prints twice of ---name---::

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

您可以看到现场演示在这里:<一href=\"http://plnkr.co/edit/tb8RpnBJZaJ73V73QISC?p=$p$pview\">http://plnkr.co/edit/tb8RpnBJZaJ73V73QISC?p=$p$pview

You can see a live demo here: http://plnkr.co/edit/tb8RpnBJZaJ73V73QISC?p=preview

为什么功能名称()被调用两次?

Why the function name() has been invoked two times?

推荐答案

在AngularJS,什么都用双花括号是的是被评估的>至少一次。

In AngularJS, anything wrapped in double curly braces is an expression that gets evaluated at least once during the digest cycle.

AngularJS通过持续运行的消化周期,直到一切都没有改变的作品。这就是它如何确保认为是先进的日期。既然你调用的函数,它的运行一次得到一个值,然后第二次看到,一切都没有改变。在下一个周期中消化,它至少会再次运行。

AngularJS works by running the digest cycle continuously until nothing has changed. That's how it ensures the view is up-to-date. Since you called a function, it's running it once to get a value and then a second time to see that nothing has changed. On the next digest cycle, it will run at least once again.

这通常是一个好主意,只调用幂等方法(如名称)从模板因为这个原因。

It's generally a good idea to only call idempotent methods (like name) from the template for this very reason.

这篇关于为什么angularjs将调用函数'名称()`两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!