UI路由器

我试图注入一个解析对象与加载数据到我的控制器,但我得到一个Unknown Provider错误:

未知提供者:configServiceProvider < - configService

这是我的代码:

StateProvider

$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>

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

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

// 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内 - '根'

// 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: { }
})

调整后的index.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路由器布局?

链接地址: http://www.djcxy.com/p/77633.html

上一篇: UI Router

下一篇: error injecting $dialog in angularjs