且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

路由器解析不会注入控制器

更新时间:2023-02-12 11:24:16

当你在绑定到路由的控制器中使用路由解析参数作为依赖注入时,你不能使用带有 ng-controller 指令的控制器,因为具有name aname 不存在.它是一个动态依赖,由路由器在实例化控制器时注入到其各自的局部视图中.

还要记住在您的示例中返回 $timeout,因为它返回一个承诺,否则您的参数将在没有值的情况下得到解决,如果您使用 $http 或其他返回承诺的服务.

 解析:{用户:['$超时',函数($超时){返回 $timeout(function() {返回{名称:'我'}}, 1000);}],

在控制器中注入解析依赖.

appControllers.controller('AppCtrl', AppCtrl);AppCtrl.$inject = ['$scope', '$rootScope','auser'];//在这里注入用户函数 AppCtrl($scope, $rootScope, auser) {var vm = 这个;vm.user = auser;}

在视图而不是 ng-controller 中,使用 ui-view 指令:

演示

I have tried everything to get ui-router's resolve to pass it's value to the given controller–AppCtrl. I am using dependency injection with $inject, and that seems to cause the issues. What am I missing?

Routing

$stateProvider.state('app.index', {
  url: '/me',
  templateUrl: '/includes/app/me.jade',
  controller: 'AppCtrl',
  controllerAs: 'vm',
  resolve: {
    auser: ['User', function(User) {
      return User.getUser().then(function(user) {
        return user;
      });
    }],
  }
});

Controller

appControllers.controller('AppCtrl', AppCtrl);

AppCtrl.$inject = ['$scope', '$rootScope'];

function AppCtrl($scope, $rootScope, auser) {
  var vm = this;
  console.log(auser); // undefined

  ...
}

Edit Here's a plunk http://plnkr.co/edit/PoCiEnh64hR4XM24aH33?p=preview

When you use route resolve argument as dependency injection in the controller bound to the route, you cannot use that controller with ng-controller directive because the service provider with the name aname does not exist. It is a dynamic dependency that is injected by the router when it instantiates the controller to be bound in its respective partial view.

Also remember to return $timeout in your example, because it returns a promise otherwise your argument will get resolved with no value, same is the case if you are using $http or another service that returns a promise.

i.e

  resolve: {
    auser: ['$timeout', function($timeout) {
      return $timeout(function() {
        return {name:'me'}
      }, 1000);
    }],

In the controller inject the resolve dependency.

appControllers.controller('AppCtrl', AppCtrl);

AppCtrl.$inject = ['$scope', '$rootScope','auser']; //Inject auser here

function AppCtrl($scope, $rootScope, auser) {
  var vm = this;
  vm.user = auser;
}

in the view instead of ng-controller, use ui-view directive:

<div ui-view></div>

Demo