在ng-init中使用$ timeout来调用函数以每2秒显示一次形状

问题描述:

我正在试图对Angular 1使用$ timeout来每隔2秒用ng-init调用一个函数。

ng-init="$timeout(sc.displaySorted(), 2000)" 

sc.displaySorted()是一个将100个排序后的图形显示到DOM上的函数。这在ng-init上是可用的,但我一直无法弄清楚它每2秒刷新一次。我也试过$ route.reload和递归。

这里是vm.displaySorted功能:

vm.displaySorted = function() { 
//calls generateFunc and pass total of 50 shapes 
var allShapes = generateFunc(50); 
//calls sortingFunc with argument of all shapes 
var sortedShapes = sortingFunc(allShapes); 
for(i = 0; i < sortedShapes.length; i++) { 
    var shape = sortedShapes[i] 
    if(shape.type === "square") { 
    vm.shapesToDisplay.push(sortedShapes[i]); 
    } 
    if(shape.type === "circle") { 
    vm.shapesToDisplay.push(sortedShapes[i]); 
    } 
} 

}; //结束vm.displaySorted

什么你正在寻找的是$interval服务。您可以使用它是这样的:在这里

$interval(displaySorted, 2000) 

注意

  • 我只是把功能,而不是它的调用(无圆括号)。

  • 在您查看ng-init="$interval(sc.displaySorted, 2000)"因为$interval你不这样做不可的观点,但在控制器(由AngularJS注射服务),所以你必须使函数的函数包装。见下面的完整示例。

angular 
 
    .module('app', []) 
 
    .controller('myctrl', function($interval) { 
 
    var vm = this; 
 
    vm.wizard = { 
 
     displaySorted: fnDisplaySorted, 
 
     init: fnInit 
 
    } 
 

 
    return vm.wizard; 
 

 
    function fnInit() { 
 
     $interval(fnDisplaySorted, 2000); 
 
    } 
 

 
    function fnDisplaySorted() { 
 
     console.log('printing'); 
 
    } 
 

 
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="app" ng-controller="myctrl as ctrl" ng-init="ctrl.init()"> 
 
</div>

+0

那岂不是需要一个函数调用:$间隔(sc.displaySorted(),2000)? –

+0

不,当你这样写时,你正在执行该功能(中间,不是你想要的)。你只需要在那里放置这个功能,这个服务就会为你完成剩下的工作(每X间隔执行一次,你想要什么:)) – lealceldeiro

+0

嗯,当我尝试时,它根本不会被调用。 –

使用$interval对于这一点,你需要把它列入控制器,请参考下面的例子。

var app = angular.module('myApp', []); 
 

 
app.controller('MyController', function MyController($scope, $interval) { 
 
    this.displaySorted = function() { 
 
    console.log("every 2 seconds"); 
 
    } 
 
    this.runThis = function(){ 
 
    $interval(this.displaySorted, 2000); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-controller='MyController as sc' ng-app="myApp" ng-init="sc.runThis()"> 
 

 
</div>

+0

我是否必须将displaySorted()设置为视图模型?我实际上尝试过任何一种方式,但它还没有工作。 –

+0

@MattLarson你能分享控制器代码吗?不是全部,只有'displaySorted'功能和控制器块。也是'sc'''范围'或'这个' –

+0

我把它加到主线程中:) –