Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start $interval immediately in AngularJS

Tags:

I have the function notifications.get() that runs every 10 seconds.

function notificationsCtrl($scope, $interval) {     $interval(function(){          $scope.notification = notifications.get();         $('.card').addClass('rotate');     }, 10000); }; 

But when the page is loaded, the function should be called once immediately. Can anyone help me?

like image 689
alexP Avatar asked Feb 24 '14 13:02

alexP


People also ask

What is $interval in AngularJS?

AngularJS's wrapper for window. setInterval . The fn function is executed every delay milliseconds. The return value of registering an interval function is a promise. This promise will be notified upon each tick of the interval, and will be resolved after count iterations, or run indefinitely if count is not defined.

How to stop interval in Angular?

You need to call unsubscribe() on the subscribe variable.

What do the services represent in AngularJS What are directives?

In AngularJS, a service is a function, or object, that is available for, and limited to, your AngularJS application. AngularJS has about 30 built-in services. One of them is the $location service.


1 Answers

You can do it like this,

  1. Define it as a function
  2. Call it immediately by function name
  3. Attach function to $interval() for execute in every 10 sec.

CODE:

function notificationsCtrl($scope, $interval) {     var fun = function(){          $scope.notification = notifications.get();         $('.card').addClass('rotate');     };     fun();     $interval(fun, 10000); }; 
like image 145
Pranav C Balan Avatar answered Oct 19 '22 04:10

Pranav C Balan