在控制器中访问ui-router解析

时间:2015-06-22 14:30:34

标签: angularjs angular-ui-router

我继续发现伟大的ui路由器。我现在专注于resolve()功能。我有一个$state基地,我在后端解析一个查询()。

$stateProvider
    .state('baseApp', {
      url: '/app',
      abstract: false,
      templateUrl: 'app/layout/baseApp.html',
      authenticate: true,
      resolve: {
        // Access API Service
        APIService: 'APIService',

        // Operators
        myObjects: function(APIService){
          // APIService is a service exposing $resource
          return APIService.myObjects.query().$promise;
        }
      }
    })
    .state('baseApp.state1', {
      url: '/state1',
      views: {
        'workspace':  {
          templateUrl: 'app/state1.html',
          controller: 'State1Ctrl',
          controllerAs: 'state1'
        }
      },
      authenticate: true
    })

我试图访问myObjects中的State1Ctrl

function State1Ctrl(myObjects) {
    ....
    console.log(myObjects);
    ....
}

我希望在控制台中看到myMobject列表打印。可悲的是,这是输出:

undefined

似乎我无法访问控制器中的承诺。你知道为什么吗?

2 个答案:

答案 0 :(得分:0)

您应该在$resource承诺中获取数据然后运行。

function State1Ctrl(myObjects) {
    ....
    cmyObjects.then(function(data){
         console.log(data)
    });
}

答案 1 :(得分:0)

问题实际上很简单:

ui-router将解析值注入与状态相关联的控制器。

要将其移入控制器,您应该将决心移至子状态

$stateProvider
.state('baseApp', {
  url: '/app',
  abstract: false,
  templateUrl: 'app/layout/baseApp.html',
  authenticate: true
})
.state('baseApp.state1', {
  url: '/state1',
  views: {
    'workspace':  {
     resolve: {
        // Access API Service
        APIService: 'APIService',

        // Operators
        myObjects: function(APIService){
          // APIService is a service exposing $resource
          return APIService.myObjects.query().$promise;
        }    
      }
      templateUrl: 'app/state1.html',
      controller: 'State1Ctrl',
      controllerAs: 'state1'
    }
  },
  authenticate: true
})

编辑:在你的具体情况下,我觉得你想要的是拥有一个父母"控制器进入你的第一个状态:

$stateProvider
.state('baseApp', {
  url: '/app',
  abstract: false,
  templateUrl: 'app/layout/baseApp.html',
  authenticate: true,
  controller: BaseAppCtrl,
  resolve: {
    // Access API Service
    APIService: 'APIService',

    // Operators
    myObjects: function(APIService){
      // APIService is a service exposing $resource
      return APIService.myObjects.query().$promise;
    }
  }
})
.state('baseApp.state1', {
  url: '/state1',
  views: {
    'workspace':  {
      templateUrl: 'app/state1.html',
      controller: 'State1Ctrl',
      controllerAs: 'state1'
    }
  },
  authenticate: true
})

您只需将这些参数注入父控制器即可。您可以访问子$ scope范围内的父$ scope。

在父控制器中:

function BaseAppCtrl($scope, myObjects) {
    ....
    $scope.myObjects = myObjects;
    console.log(myObjects);
    ....
}

function State1Ctrl($scope) {
    ....
    console.log($scope.myObjects);
    ....
}

在这种情况下,console.log都应显示值。

您可以在this plunker

上看到它

希望它有所帮助。