AngularJS - UI 路由器 - 无法使用解析为我的控制器提供数据



我正在尝试将包含加载数据的解析对象注入我的控制器,但出现Unknown Provider错误:

未知提供程序:配置服务提供程序<- 配置服务

这是我的代码:

状态提供程序

$stateProvider
    .state('index', {
        abstract: true,
        url: "/index",
        templateUrl: "#",
        resolve: {                
            configService: function () {
                return {
                    "helloText": "Welcome in Test Panel"
                };
            }
        }
    })

控制器

function MainCtrl($scope, configService) {
    $scope.config = configService;
};
angular.module('dot', ['ui.router'])
    .config(config)
    .controller('MainCtrl', MainCtrl)

片段

function config($stateProvider, $urlRouterProvider) {
  $urlRouterProvider.otherwise("#");
  $stateProvider
    .state('index', {
      abstract: true,
      url: "/index",
      templateUrl: "#",
      resolve: {
        configService: function() {
          return {
            "helloText": "Welcome in Test Panel"
          };
        }
      }
    })
};
function MainCtrl($scope, configService) {
  $scope.config = configService;
};
(function() {
  angular.module('dot', [
      'ui.router', // Routing
    ])
    .config(config)
    .run(function($rootScope, $state) {
      $rootScope.$state = $state;
    })
    .controller('MainCtrl', MainCtrl)
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.min.js"></script>
<div ng-app="dot">
  <div ng-controller="MainCtrl as main">
    <div ui-view>
    </div>
  </div>
</div>

就像我的解析对象是在控制器加载后定义的......我是 angularJS 的新手,我觉得我肯定错过了一些非常明显的东西。

谢谢。

ng-controllerUI-Router 状态resolve不兼容。这就是为什么你的"另一个世界"MainCtrl"不能注入UI路由器中定义的解析/服务。

但是有一个简单的方法,只需将其转换为状态:

// brand new root state, providing root (index.html) stuff
// not effecting url or state names
.state('root', {
    abstract: true,
    template: '<div ui-view=""></div>', // a target for child state
    resolve: {                
        configService: function () {    // ready for any state in hierarchy
            return {
                "helloText": "Welcome in Test Panel"
            };
        }
    },
    // brand new line, with 'MainCtrl', which is part of UI-Router now
    controller: 'MainCtrl',
})

原始状态"索引"现在将被放置在一个真实但抽象的 url 中,不会影响状态 - "root"

// adjusted state
.state('index', {    // will be injected into parent template
    parent: 'root'
    abstract: true,
    url: "/index",
    templateUrl: ...,
    // resolve not needed, already done in root
    //resolve: { }
})

调整后的指数.html

<div ng-app="dot">
  <div ui-view="></div> // here will be injected root state, with 'MainCtrl'
  //<div ng-controller="MainCtrl as main">
  //  <div ui-view>
  //  </div>
  //</div>
</div>

也许还要检查 - ui-router 中左边栏布局的嵌套状态或视图?

最新更新