简体   繁体   English

在我的情况下如何设置间隔时间

[英]How to set interval time in my case

I am trying to set interval in my app and have something like this 我正在尝试在我的应用中设置时间间隔,并且有类似这样的内容

html html

 <div class="text">
     {{currentItem.name}}
 </div>
<ul>
    <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li>
</ul>

Controller 控制者

 $scope.index = 0;
 $scope.currentItem = $scope.items[$scope.index];  // set the first item

//The interval start 3 second after the app is loaded
$scope.startInt = $interval(function() {
    $scope.currentItem = $scope.items[$scope.index];
    $scope.index++;

    if(scope.index === $scope.items.length) {
        $scope.index=0;
    }
}, 3000)

The above codes will start the interval 'AFTER' the page is loaded for 3 sec. 上面的代码将在页面加载后的“ AFTER”间隔开始3秒钟。 I was hoping to start the interval immediately when the page first loads. 我希望在页面首次加载时立即开始间隔。 Is there anyway to do this? 反正有这样做吗? Thanks a lot! 非常感谢!

One simple solution: 一种简单的解决方案:

var intervalWork = function () {
    $scope.currentItem = $scope.items[$scope.index];
    $scope.index++;

    if(scope.index === $scope.items.length) {
        $scope.index=0;
    }
};

intervalWork();

//The interval start 3 second after the app is loaded
$scope.startInt = $interval(intervalWork, 3000)

Convert your anonymous function to a named function. 将您的匿名函数转换为命名函数。 Then call the function before using the interval 然后在使用间隔之前调用函数

function IntervalFunction() {
    $scope.currentItem = $scope.items[$scope.index];
    $scope.index++;

    if(scope.index === $scope.items.length) {
        $scope.index=0;
    }
}

IntervalFunctin();
$scope.startInt = $interval(IntervalFunction, 3000);
function notificationsCtrl($scope, $interval) {
    var fun = function(){ 
        $scope.currentItem = $scope.items[$scope.index];
        $scope.index++;

        if(scope.index === $scope.items.length) {
            $scope.index=0;
        };
    fun();
    $interval(fun, 3000);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM