uglycode uglycode - 6 months ago 22
AngularJS Question

Run a function only the first time when angular gets loaded

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

routeProvider
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
routeProvider
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
run
and then broadcast the event when page gets loaded, but there are no event listeners - I guess that is because the
run
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?

UPDATE

Use case:


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

  • when pages gets loaded, a
    $http.get
    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 (
    routeProvider
    ) 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)


T J T J
Answer

Use the run method:

app.run(function(yourService){
  yourService.cacheRandomContent();
});

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){
  yourService.getCachedRandomContent().then(function(resp){
    $scope.data = resp.data;
  });
});

Your service would be something like:

app.service('yourService',function($http){
  var promise;
  return {
   cacheRandomContent: function(){
     promise = $http.get();
   },
   getCachedRandomContent : function(){
       return promise;
   }
  }
});
Comments