我正在学习angular.js,想知道是否有办法从while循环更新视图。我有一个单击的按钮,它调用带有while循环的函数,该循环为每次迭代增加一个变量。有一个取消循环的按钮。我已阅读并稍微理解了角度用于更新视图的$ apply / $ digest循环。我也修改了$ interval并让它工作,但最终它还不够快,我想最终做到这一点。
那么有没有办法获得在打印到屏幕的while循环中递增的变量。这是我到目前为止的代码。
LearningAngular.js
var myApp = angular.module("myApp", []);
myApp.controller("myController", myController);
function myController($scope, $interval) {
var count = true;
$scope.counter = 0;
$scope.start_count = function(){
//promise = $interval(function() {
// $scope.counter++;
//},1);
while (count == true) {
$scope.counter++;
}
}
$scope.stop_counting = function(){
//$interval.cancel(promise);
count = false;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Learning Angular</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myController">
<button ng-click="start_count()">Start Counting</button><br>
Counter: <span>{{counter}}</span><br>
<button ng-click="stop_counting()">Stop Counting</button>
</body>
</html>
修改
当ng-click调用代码进入while循环的start_count()
函数时会发生什么。如果我在chrome中打开调试器并单击按钮然后在$scope.counter++
处设置一个断点,我可以看到计数器正在递增。它只是没有在屏幕上显示。我不想使用提供的setInterval或$ interval函数,因为它们对于我打算使用代码的速度不够快。在坚果壳中,我将比较用户选择的模拟功率球数与计算机绘制的功率球数。 setInterval和$ interval函数对此很有用,但需要很长时间才能获得。计算机可以在几秒钟内检查几百万,但如果它受间隔限制则不能。
答案 0 :(得分:0)
虽然循环已实现在$ apply / $ digest的单次迭代中发生,但它永远不会看到计数器的更改。我不确定使用angular实现期望行为的正确方法是什么,但您可以使用setInterval或setTimeout函数使用纯javascript轻松实现此功能。逻辑将与您实现的完全相同,除非您调用setInterval而不是启动while循环。 希望这会有所帮助。
答案 1 :(得分:0)
因为你无休止的循环。您的点击停止观看未被触发。
无尽循环背后的原因:一旦作为参数传递给while。它的局部变量不会被覆盖,所以它变成了无限循环
问题:您正在调用
count
,它是模型值而不是方法start_counting
。 解决方案:将$scope
和$interval
作为第二个参数传递给控制器方法。以下是工作演示。
var myApp = angular.module("myApp", []);
myApp.controller('myController', ['$scope', '$interval',
function($scope, $interval) {
$scope.counter = 0;
var stop;
$scope.start_count = function() {
if (angular.isDefined(stop)) return;
$scope.counter++;
stop = $interval(function() {
$scope.counter++;
}, 100);
}
$scope.stop_counting = function() {
if (angular.isDefined(stop)) {
$interval.cancel(stop);
stop = undefined;
}
}
}
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myController">
<button ng-click="start_count()">Start Counting</button>
<br> Counter: <span>{{counter}}</span>
<br>
<button ng-click="stop_counting()">Stop Counting</button>
</body>
&#13;
参考:
https://docs.angularjs.org/api/ng/service/ $间隔
ng-click
的简单示例:https://docs.angularjs.org/api/ng/directive/ngClick
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
<span>
count: {{count}}
</span>
答案 2 :(得分:0)
我想也许你的错误是你在ng-click中使用的función的名字,因为在控制器中你称之为start_count但是在ng-click count()中