简体   繁体   中英

Inject controller in $routeProvider resolve method

Following the main answer here , I've tried to do the same, with the exception that my controller is isolated. I get this:

Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
ReferenceError: myController is not defined

I only get this when the resolve: parameter is present. How can I work around this one ?

Route config:

 .state("my.jobs", {
                     url: "/my/:jobId",
                     templateUrl: "Views/my/index.htm",
                     controller: "myController",
                     resolve: myController.resolve  // the root of all evil here
                 })

controller:

(function (ng, app) {

    "use strict";

    var ctrl = app.controller(
        "myController",
        ['$scope', 'job',
        function ($scope, job) {
            $scope.job = job;
        }]);

    ctrl.resolve = {
        job: function ($q, $stateParams, batchService) {
            var deferred = $q.defer();
            jobService.loadJob($stateParams.jobId, true)
                    .then(deferred.resolve, deferred.reject);
        },
        delay: function ($q, $defer) {
            var delay = $q.defer();
            $defer(delay.resolve, 1000);
            return delay.promise;
        }
    };
})(angular, myApp);

I don't want to make the controller a global function, I like it isolated as it is.

In your case you could create one service, that you can consume inside your resolve function.

app.factory('resolveService', ['$q', '$stateParams', 'batchService','jobService',function($q, $stateParams, batchService,jobService ) {
    return {
        job: function($q, $stateParams, batchService) {
            var deferred = $q.defer();
            jobService.loadJob($stateParams.jobId, true).then(deferred.resolve, deferred.reject);
            return delay.promise;
        },
        delay: function($q, $defer) {
            var delay = $q.defer();
            $defer(delay.resolve, 1000);
            return delay.promise;
        }
    }
}]);

Then the config code will be

.state("my.jobs", {
    url: "/my/:jobId",
    templateUrl: "Views/my/index.htm",
    controller: "myController",
    resolve: {
        resolveService: "resolveService" //this resolves to a service 
    }
});

For more info look at this reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM