문제

Before voting this down, yes this question has been asked here already, and answered, but the answers are not satisfactory. They all correctly suggest to add the controller in the route configuration, but this is not the case here.

The expected behavior for the routeProvider's resolve object xxx is to be injected into the controller:

var app = angular.module('X', [])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/',{
        controller:'XCtrl',
        templateUrl: 'x.html',
        resolve: {
            xxx: function () {
                return 'XXX from routing config.';
            }
        }
    })
}])
.controller('XCtrl', function($scope, xxx) {
    console.log('xxx = '+xxx);
});

The console should get a xxx = XXX from routing config. entry.

Instead, the code extract above fails with:

Error: [$injector:unpr] Unknown provider: xxxProvider <- xxx
http://errors.angularjs.org/1.2.10/$injector/unpr?p0=xxxProvider%20%3C-%20xxx
 .. etc.

XCtrl is not declared in the HTML with a ng-controller directive but only defined in the routing configuration.

도움이 되었습니까?

해결책

If you have several entry in the routing configuration using the same controller, all properties that are injected in the controller must appear in all instances of the resolve object:

var app = angular.module('X', [])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
    .when('/',{
        controller:'XCtrl',
        templateUrl: 'x.html',
        resolve: {
            xxx: function () {
                return 'XXX from routing config.';
            }
            another: // ...
        }
    })
    .when('/page2',{
        controller:'XCtrl',
        templateUrl: 'x/p2.html',
        resolve: {
            xxx: function () {
                return 'XXX from routing config.';
            }
        }
    })
}])
.controller('XCtrl', function($scope, xxx) {
    console.log('xxx = '+xxx);
});

The resolve objects don't have to be promises, straight data returning from a function as above also works. Promises are useful to prevent the routing if one of them is rejected.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top