gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:36:16 24 4
gpt4 key购买 nike

代码很简单:

<!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>

您会看到这里有一个 name函数,我们只在体内调用它一次。但是在控制台中,它会打印两次 ---name---::
---name---:Wed Feb 20 2013 14:38:12 GMT+0800 (中国标准时间)
---name---:Wed Feb 20 2013 14:38:12 GMT+0800 (中国标准时间)

您可以在此处观看现场演示: http://plnkr.co/edit/tb8RpnBJZaJ73V73QISC?p=preview

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

最佳答案

在AngularJS中,用大括号括起来的任何东西都是expression,它在摘要循环中至少被评估一次。

AngularJS通过连续运行摘要循环直到没有任何变化来工作。这样可以确保 View 是最新的。自调用函数以来,它运行一次以获取值,然后再次运行以查看没有任何变化。在下一个摘要周期,它将至少再次运行。

出于这个原因,通常仅从模板中调用幂等方法(例如name)是一个好主意。

关于angularjs - 为什么angularjs会两次调用 `name()`函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14973792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com