在角度js和角度路由器中使用一次解析函数到几个控制器

时间:2018-01-24 13:12:37

标签: angularjs angular-ui-router

Ui路由器看起来像:

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

我的路线:

 .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();
                           }
                       }
                     },

我只想调用getData一次而不是将它注入每个控制器 如果我在每个控制器中执行此操作,则意味着我在加载时从服务器调用getData两次。

我尝试使用控制器继承,但它要求注入该服务

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

我怎样才能让它像继承一样? 我需要移动它来运行该功能吗?如果是,我是否必须使用rootScope在控制器中获取该数据?

1 个答案:

答案 0 :(得分:1)

尝试将解决方案放在父级上:

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

然后,您需要在每个视图控制器上添加getData作为依赖项:

// Controller
function test1ontroller(getData) {

}