我在 script.js 文件中有这段代码:
scotchApp.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
scotchApp.controller('SharedController',['$scope', 'myService', function($scope) {
myService.set('hello');
$scope.message = myService.get();
}]);
当我尝试上传使用此代码的 html 时,我进入了 chrome(F12 模式): angular.js:12722 ReferenceError: myService 未定义
为什么?
最佳答案
您从未将您的服务注入(inject)到 Controller 中。正确代码:
scotchApp.controller('SharedController', ['$scope', 'myService', function($scope, myService) {
myService.set('hello');
$scope.message = myService.get();
}]);
注意 Controller 函数签名 function($scope, myService) {...}
。
关于javascript - 为什么我在 Angular 页面中收到 "service is not defined"错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032623/