我试图读取JSON文件并在网站上发布其数据。我应该告诉你我是棱角分明的,所以我不知道我的app.js中发生了什么 我得到的错误是:
ReferenceError: MyService is not defined
at new <anonymous> (app.js:20)
at Object.invoke (angular.min.js:41)
at T.instance (angular.min.js:86)
...
我的app.js
var app = angular.module('MyApp',[]);
app.service("MyService", function($http, $q)
{
var defferd = $q.defer();
$http.get('JSON/nosaints.json').then(function(data){
defferd.resolve(data);
});
this.GetPlayers = function()
{
return defferd.promise;
}
}).controller("MyController", function($scope){
var promise = MyService.GetPlayers();
promise.then(function(data)
{
$scope.team = data;
console.log($scope.team);
});
})
的index.html
<body ng-app="MyApp">
<div class="inner cover" ng-controller="MyController">
<ul>
<li ng-repeat="player in team">
//print from player here
</li>
</ul>
</div>
</body>
答案 0 :(得分:0)
服务是可注入的依赖项。您需要将它们注入您想要使用它们的位置(即在控制器,指令,其他服务......):
app.controller("MyController", function($scope, MyService){
var promise = MyService.GetPlayers();
promise.then(function(data)
{
$scope.team = data;
console.log($scope.team);
});
});
顺便说一句,如果您想稍后缩小代码,则应使用strict dependency injection:
var controllerFunc = function($scope, MyService){
var promise = MyService.GetPlayers();
promise.then(function(data)
{
$scope.team = data;
console.log($scope.team);
});
};
controllerFunc.$inject = ["$scope", "MyService"];
app.controller("MyController", controllerFunc);