正在构建一个角度应用程序,但是服务或工厂未定义错误。具体来说"无法读取setName undefined"的属性。我已经here找出了我的错误。甚至改变了我的语法,认为我可能有一些不合适的东西,但仍然抛出一个未定义的错误。
这是控制器:
(function() {
"use strict";
angular
.module("app", [])
.controller("mainCtrl", ["$scope", mainCtrl]);
function mainCtrl($scope, productService) {
$scope.testService = productService.setName("Data Service");
}
}());
这是服务脚本:
(function() {
"use strict";
angular
.module("app")
.service("productService", function() {
var serviceObj = {};
serviceObj.name = '';
serviceObj.setName = function(newName) {
serviceObj.name = newName;
};
return serviceObj;
});
}());
最初,我的服务是:
(function() {
"use strict";
angular
.module("app")
.service("productService", setName);
function setName(newName) {
var serviceObj = {};
serviceObj.name = '';
serviceObj.setName = function(newName) {
serviceObj.name = newName;
};
return serviceObj;
}
}());
答案 0 :(得分:2)
我最近遇到了这个问题,似乎必须在创建控制器之前定义该函数。我建议按以下方式进行:
(function () {
"use strict";
//function
function mainCtrl($scope, productService) {
$scope.testService = productService.setName("Data Service");
}
//Controller and Module Init
angular
.module("app", [])
.controller("mainCtrl", mainCtrl);
//Inject requirements (This is needed for Minification)
mainCtrl.$inject = ["$scope", "productService"];
}());