Tuz
Tuz

Reputation: 1990

Using resolve functions once in angular js and angular router to few controllers

Ui router looks like:

<div ui-view="test1">
<div ui-view="test2">

My routing:

 .state('testsPage', {
                  url: "/",
                  // templateUrl: "public/src/settings/settings.php",
          views: {
             'test1': {
                       templateUrl: 'public/src/test2.html',
                       controller: 'test2Controller',
                       controllerAs: 'vm',
                       resolve: {
                            getData: function(testService) {
                              return testService.getdata();
                            }
                       }
                     },
                     'test2': {
                       templateUrl: 'public/src/test1.html',
                       controller: 'test1ontroller',
                       controllerAs: 'vm',
                       resolve: {
                           getData: function(testService) {
                               return testService.getdata();
                           }
                       }
                     },

I want to call getData only once and not inject it the each controller If I do that in each controller it means that I call to getData from server two times in loading.

I tried to use controller inheritance but it ask to inject that service

    // Inherit from Base Controller
    angular.extend(vm, $controller('baseController', {
        getData: getData,
        testService: testService,
        $rootScope: $rootScope
    }));

How can I make it like inheritance? Do I need to move it to run the function? If yes do I have to use rootScope to get that data in the controller?

Upvotes: 1

Views: 46

Answers (1)

AnthW
AnthW

Reputation: 543

Try putting the resolve on the parent:

.state('testsPage', {
  url: '/',
  views: ...,
  resolve: {
    getData: function(testService) {
      return testService.getdata();
    }
  }
  ...
}

You would then need to add getData as a dependancy on each views controller:

// Controller
function test1ontroller(getData) {

}

Upvotes: 1

Related Questions