我的工厂AngularJS运行了2次?
My index.php我的工厂AngularJS运行了2次?,angularjs,factory,Angularjs,Factory,My index.php <!doctype html> <html lang="en" ng-app="abc"> <head> <meta charset="utf-8"> <title>Google Phone Gallery</title> <base href="" /> </head> <body> <div ng-controller=
<!doctype html>
<html lang="en" ng-app="abc">
<head>
<meta charset="utf-8">
<title>Google Phone Gallery</title>
<base href="" />
</head>
<body>
<div ng-controller="test">
{{sayhello()}}
</div>
</body>
<script src="js/core/angular.min.js"></script>
<script src="js/modules/example/controllers/controller.js"></script>
</html>
你们能告诉我为什么我的警报运行了两次吗
但如果我改变:
<div ng-controller="test">
{{sayhello()}}
</div>
{{sayhello()}}
致:
它只运行一次?你们能告诉我怎么做吗?这是设计的
所有角度表达式(包括插值字符串{sayhello()}
和$watch()
中的表达式)都将重复重新计算(对于每个$digest
周期),以检测模型中的更改并相应地更新视图
即使是空的$watch()
也会有相同的行为,有关讨论,请参阅
如果您想了解更多关于angularjs的数据绑定及其摘要循环的工作原理,请阅读以下文章:
你看到的是Angular的消化循环是如何工作的。它将继续计算视图绑定到的表达式,直到没有任何更改。这意味着它必须至少对绑定求值两次。在这种情况下,表达式计算为
未定义
,并且摘要循环停止
要仅对其求值一次,请将该值指定给作用域上的属性
<div ng-controller="test">
{{greeting}}
</div>
app.controller('test', function($scope, greeter){
$scope.sayhello = function(){
greeter.greet();
};
$scope.greeting = $scope.sayhello();
});
{{问候语}
应用控制器(“测试”,功能($scope,greeter){
$scope.sayhello=函数(){
问候者;
};
$scope.greeting=$scope.sayhello();
});
@AHSR0x如果您觉得这个答案有帮助,请接受。谢谢您的回答
<div ng-controller="test">
<input type="button" value="Click 2 run" ng-click="sayhello()">
</div>
<div ng-controller="test">
{{greeting}}
</div>
app.controller('test', function($scope, greeter){
$scope.sayhello = function(){
greeter.greet();
};
$scope.greeting = $scope.sayhello();
});