Angular UI-路由器 - 直接在模板 url 上使用 "resolve"

Angular UI-Router - using "resolve" directly on template url

我正在使用 UI-Router 并希望将路由更改为 'component based'。所以我不想定义控制器/模板,而是想像这样使用它:

.state('issue', {
    url: '/someUrl/:number',
    template: '<my-directive></my-directive>',
    resolve: {
      data: function(dataService) {
        return dataService.getData().then(function(response) {
            console.log(response.data);
            return response.data;
        });
      }
    }
 })

现在,我知道使用 Angular 的 ngRoute 我可以直接在模板中使用已解析的数据,例如:

 $routeProvider
      .when('/', {
        template: `<my-directive data="resolve.data"></my-directive>`,
        resolve: {
          data: function (dataService) {
            return dataService.getData();
          }
        }
      }) 

我无法使用 UI-Router(值未定义)。

我做错了什么吗?是否可以使用 ui-路由器?

UI-Router 的要点是 - resolve 的结果可用于 controller (与模板相关)。所以,我们可以这样做:

.state('issue', {
    url: '/someUrl/:number',
    template: '<my-directive data="stateCtrlData"></my-directive>',
    controller: function($scope, data) { $scope.stateCtrlData = data },
    resolve: {
      data: function(dataService) {
        return dataService.getData().then(function(response) {
            console.log(response.data);
            return response.data;
        });
      }
    }
  })

data 被传递到控制器,我们从它的作用域传递给指令。

如果你的意思是注入你的数据服务,那么你可以这样做(记住''是告诉注入):

state('issue', {
        url: '/someUrl/',
        template: '<my-directive data="pep.data"></my-directive>',
        controller: function( data) { this.data = data },
        controllerAs: 'pep',  
        resolve:{
                 dataSvc : 'YourDataSvc',
                 campaign : function(dataSvc){
                         return dataSvc.getData();

                }
             }

请记住,如果您想添加其他视图或子状态,则需要 ui-view

实际上你可以(仅在 ui-router v0.3.2 中测试过)

有一个未记录 $resolve 变量自动注入控制器。 只需在state中添加'controllerAs' 属性如下,即可在模板中使用$resolve:

.state('issue', {
    url: '/someUrl/:number',
    template: '<my-directive data="vm.$resolve.data"></my-directive>',
    controllerAs: 'vm',
    resolve: {
      data: function(dataService) {
        return dataService.getData().then(function(response) {
            console.log(response.data);
            return response.data;
        });
      }
    }
 })