这是我想要做的事情。我在我的控制器中设置更新模型的间隔:
myapp.js
----------
$scope.myModel = myArray[$scope.currentIndex];
var changeModel = function() {
$scope.currentIndex += 1; //increment index
$scope.myModel = myArray[$scope.currentIndex]; //reset model
}
setInterval(changeModel, 1000);
然后我有一个访问该更新模型的模板:
my-template.html
-----------------
<div>{{$scope.myModel}}</div>
我看到的是模板每秒都没有刷新。这不是事件一致刷新。在查看页面时,div中的文本会突然跳转,有时会在不到一秒钟后跳转。我怀疑这与我自己的changeModel
方法和角度所做的内部视图更新之间的不匹配有关。还有其他人遇到过这个问题吗?如果是这样,你是如何解决的?
答案 0 :(得分:1)
由于setInterval代码在angular之外运行,因此您需要运行一个范围。$ apply(或更安全的范围。$ evalAsync)。快速jsfiddle来演示。
试试这个:
$scope.myModel = myArray[$scope.currentIndex];
var changeModel = function() {
$scope.currentIndex += 1; //increment index
$scope.myModel = myArray[$scope.currentIndex]; //reset model
//This will make sure angular runs a digest loop which will update your data.
$scope.$evalAsync();
}
setInterval(changeModel, 1000);
$ interval在版本1.2中可用,并且更合适,因为这将不再需要$ evalAsync来运行摘要循环。 Example of using $interval