0

For some reason I have a problem wrapping my head around Angular logic, but I am determined to understand this.

I am trying to run a function at application start that loops through an object and stores the result globaly. I am trying to do this through a service.

first question: Should I use .run() to initialize this or in controller on first route?

here is my code:

var coreServices = angular.module('coreServices', []);

coreServices.service('addObject',["$http","$rootScope", function($http,$rootScope) {
   var _index = {};
   addObj = function(a,b){
      //loop through a  until _index object is built
   }
   // once _index is completely built assign to $rootScope.structure
}]);

I cannot seem to get this right. Everytime I log $rootScope.structure in my controller it is undefined. What is the best way to do something like this? $scope.watch? promises?

Jason Spick
  • 6,028
  • 13
  • 40
  • 59

1 Answers1

0

You want to use the run function to init your service function after injecting it:

app.run(['addObject', function (addObject) {
    addObject.addObj();
}])

app.service('addObject', ['$rootScope', function ($rootScope) {
    var _index = {};
    this.addObj = function(a,b){
      //loop through a  until _index object is built
      //do something to $rootScope.yourvariable
    }
}])
btm1
  • 3,866
  • 2
  • 23
  • 26