【发布时间】:2016-06-29 18:44:37
【问题描述】:
我有一个带有控制器和服务的 Angular 应用程序。我从控制器调用服务,服务进行后端调用,应该调用控制器中的另一个函数。我能够从控制器调用服务,但无法调用控制器中的函数。
这里是代码。控制器:
(function(){
angular.module("addressModule")
// The controller for the standardized Address
.controller('myController', ['$resource','myService', myControllerFunction]);
myControllerFunction.$inject = ['addressConfig', 'myService', '$resource'];
function myControllerFunction (addressConfig, myService, $resource, $scope) {
var vm = this;
// cannot show what the model is
vm.model = "some model";
myService.callGISFromService(vm.model);
this.callFunctionInController = function(){
console.log("The controller function is called");
}
}
})();
服务的代码是
(function(){
angular.module('addressModule')
.service('myService', ['$resource', myServiceFunction]);
myServiceFunction.$inject = ['$resource'];
function myServiceFunction ($resource) {
this.callGISFromService = function (model) {
var urlForTheGISCall = "some URL";
var resource = $resource(urlForTheGISCall);
console.log("control is in the service");
resource.get().$promise
.then(function successCallback(response) {
this.callFunctionInController();
}), function errorCallback(response) {
console.log("the backend call did not work");
}
};
}
})();
我能够进行后端调用并获取所需的数据,但无法调用控制器中的函数。
控制台报错:
TypeError: this.callFunctionInController is not a function
【问题讨论】:
-
$inject数组不是必须与控制器中的参数顺序相同吗?你把顺序搞混了。 -
你也注入了两次,一次使用括号语法,一次使用 $inject
-
@Daniel_L 我已经更改了订单,但没有任何区别。
-
@koox00 如果我不注入两次,应用程序将无法正常工作。
-
删除控制器中的数组表示法,只用注入服务注入,也注入 $scope 并注意顺序。如果您不使用缩小,应用程序即使完全没有注入也应该可以运行。
标签: javascript angularjs