在主要答案here之后,我试图做同样的事情,除了我的控制器是孤立的。 我明白了:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to:
ReferenceError: myController is not defined
我只在resolve:
参数出现时才会这样做。
我该如何解决这个问题?
路线配置:
.state("my.jobs", {
url: "/my/:jobId",
templateUrl: "Views/my/index.htm",
controller: "myController",
resolve: myController.resolve // the root of all evil here
})
控制器:
(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);
我不想让控制器成为一个全局函数,我喜欢它是孤立的。
答案 0 :(得分:1)
在您的情况下,您可以创建一个服务,您可以在解析功能中使用该服务。
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;
}
}
}]);
然后配置代码将是
.state("my.jobs", {
url: "/my/:jobId",
templateUrl: "Views/my/index.htm",
controller: "myController",
resolve: {
resolveService: "resolveService" //this resolves to a service
}
});
有关详细信息,请查看this reference