这是我的 html:
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<script type="text/javascript" src="services.js"></script>
<div ng-app="myApp" ng-controller="myCtrl2">
hello {{x}}
</div>
<script>
var app=angular.module("myApp", []);
app.controller("myCtrl2", ['$scope','$location', function($scope, $location) {
myService.set("world");
$scope.x=myService.get();
}]);
</script>
</body>
</html>
这是我的 services.js 文件:
var app=angular.module("myApp", []);
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}main.html
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
为什么我没有得到 hello world,而是 chrome 开发工具说:ReferenceError: myService is not Defined
最佳答案
您需要纠正一些事情
不要在 html 页面上重新创建
myApp
模块,这会破坏旧的已注册模块组件。而是使用由services.js
创建的现有myApp
模块。var app=angular.module("myApp", []);
应该是
var app=angular.module("myApp");
在 Controller 中使用服务之前先注入(inject)服务。
app.controller("myCtrl2", ['$scope','$location', 'myService', function($scope, $location, myService) {
关于javascript - 无法从外部js文件访问 Angular 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977201/