我有一个带有以下代码的角度模块:
angular.module('sampleModule', [])
.service('myService', [function () {
this.showAlert = function () {
alert("Hello");
};
this.sum = function (a, b) {
return a + b;
};
}])
.controller('SampleCtrl', ['myService', '$scope', function ($scope, myService) {
this.doSum = function () {
var result = myService.sum(1, 2);
alert(result);
};
}]);
当我调用doSum时,我得到:
TypeError:myService.sum不是函数
有什么想法吗?谢谢!
答案 0 :(得分:3)
您的控制器DI错误 - 请注意参数的顺序:
.controller('SampleCtrl', ['$scope', 'myService', function ($scope, myService) {
this.doSum = function () {
var result = myService.sum(1, 2);
alert(result);
};
}]);
答案 1 :(得分:1)
注射测序的问题不合适。 $ scope应该在myService之前。
Correct code:
.controller('SampleCtrl', ['$scope', 'myService', function ($scope, myService) {
this.doSum = function () {
var result = myService.sum(1, 2);
alert(result);
};
}]);