Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why angularjs will invoke function `name()` twice?

Tags:

The code is simple:

<!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 (中国标准时间)

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

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

like image 335
Freewind Avatar asked Feb 20 '13 06:02

Freewind


1 Answers

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

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.

like image 126
Josh David Miller Avatar answered Oct 28 '22 10:10

Josh David Miller