为什么以下代码不会每秒使用新元素更新list-group
?
的index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
<div class="panel panel-default">
<div class="panel-heading">ng-repeat with bootstrap list-item</div>
<div class="panel-body">
<div class="list-group">
<button type="button" class="list-group-item" ng-repeat="item in data">
{{item}}
</button>
</div>
</div>
</div>
</body>
</html>
的script.js
var app= angular.module("MyApp", []);
app.controller("MyController", function($scope) {
$scope.data = ["one", "two", "three", "four"];
window.setInterval(function() {
console.log("setTimeout");
$scope.data.push("five");
}, 1000);
});
我错过了什么?
提前致谢。
答案 0 :(得分:0)
setInterval
会在角度上下文中运行interval
函数,这将不会使角度消化循环系统运行摘要周期。结果的结果不会更新。
因此,对于相同的角度,提供了一个名为$interval
的服务,该服务在每个指定的interval
之后启动一个摘要周期(您可以将事件转为摘要周期)。这就是使用$interval
代替setInterval
的原因。
//inject $interval before using it.
$interval(function() {
console.log("setTimeout");
$scope.data.push("five");
}, 1000);
答案 1 :(得分:0)
如果您想使用 setInterval
$scope.$apply();
使用角度,您可以使用 $interval
<强>样本强>
var app= angular.module("MyApp", []);
app.controller("MyController", function($scope) {
$scope.data = ["one", "two", "three", "four"];
window.setInterval(function() {
console.log("setTimeout");
$scope.data.push("five");
$scope.$apply();
}, 1000);
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
<div class="panel panel-default">
<div class="panel-heading">ng-repeat with bootstrap list-item</div>
<div class="panel-body">
<div class="list-group">
<button type="button" class="list-group-item" ng-repeat="item in data">
{{item}}
</button>
</div>
</div>
</div>
</body>
</html>