uglycode uglycode - 2 years ago 212
AngularJS Question

Run a function only the first time when angular gets loaded

I'm using angular-seed template (angular 1) and I have

setup and such, now I want to execute a function (which resides in a factory), but only the very first time when the page gets loaded. I found many solutions for this, but I don't want to execute the code each time the users switches between tabs (via
of course, page doesn't get reloaded) - the code must be executed only when the whole page gets (re)loaded.

How should I approach this? I tried to call the function from
and then broadcast the event when page gets loaded, but there are no event listeners - I guess that is because the
part gets executed before the controllers are setup, so there are no listeners attached at the time when the event gets broadcast.

So, any suggestions how to approach this?


Use case:

  • when user types the url in the page, the page gets loaded

  • when pages gets loaded, a
    request is performed, which gets a random content

  • this content can be changed only by clicking a button, to explicitly request a change of content.

  • if users clicks to a different page e.g. view2 (
    ) and then back to the view1, the content must not change

  • when users refreshes the page (F5), the content changes again (or as already stated, by a click of a button)

Answer Source

Use the run method:{

It runs only once after the app is bootstrapped and services are created.

To access the data in controller, just inject the same service:

app.controller('someCtrl',function($scope, yourService){
    $ =;

Your service would be something like:

  var promise;
  return {
   cacheRandomContent: function(){
     promise = $http.get();
   getCachedRandomContent : function(){
       return promise;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download