Reputation: 799
I am trying to set interval in my app and have something like this
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. I was hoping to start the interval immediately when the page first loads. Is there anyway to do this? Thanks a lot!
Upvotes: 0
Views: 66
Reputation: 1757
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);
};
Upvotes: 1
Reputation: 30557
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);
Upvotes: 1
Reputation: 70075
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)
Upvotes: 1