我有以下代碼(從書角向上和運行):
angular.module('fifaApp')
.controller('TeamListCtrl', ['FifaService',
function(FifaService) {
var self = this;
self.teams = [];
FifaService.getTeams().then(function(resp) {
self.teams = resp.data;
});
}])
.factory('FifaService', ['$http',
function($http) {
return {
getTeams: function() {
return $http.get('/api/team');
},
getTeamDetails: function(code) {
return $http.get('/api/team/' + code);
}
}
}])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
});
});
然後在服務器上:
app.get('/api/team', function(req, res) {
res.send(FIFA.TEAMS_LIST);
});
我試着以這種方式重寫它,使用$resource
,但它不顯示templateUrl
views/team_list.html
。
我的解決辦法:
angular.module('fifaApp','ngResource')
.controller('TeamListCtrl', ['FifaService',
function(FifaService) {
var self = this;
self.teams = [];
FifaService.query().$promise
.then(function(resp) {
self.teams = resp.data;
});
}])
//`$resource` now instead of `$http`
.factory('FifaService', ['$resource',
function($resource) {
return $resource('/api/team');
}])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/team_list.html',
controller: 'TeamListCtrl as teamListCtrl'
});
});
爲什麼我看不到views/team_list.html
? 問候
<div class="team-list-container">
<div class="team"
ng-repeat="team in teamListCtrl.teams | orderBy: 'rank'">
<div class="team-info row">
<div class="col-lg-1 rank">
<span ng-bind="team.rank"></span>
</div>
<div class="col-sm-3">
<img ng-src="{{team.flagUrl}}" class="flag">
</div>
<div class="col-lg-6 name">
<a title="Image Courtesy: Wikipedia"
ng-href="#/team/{{team.code}}"
ng-bind="team.name"
style="color: cadetblue;"></a>
</div>
</div>
</div>
</div>
爲什麼要移除'$ promise'? var User = $ resource('/ user /:userId',{userId:'@ id'}); (函數(用戶){0} {0}} {scope.user = user; });用戶.get({userId:123}) 。$ promise.then作品例如。來自Angular文檔。 – user1665355
也許你的意思是$ q.defer()。我從來沒有見過使用$ promise,甚至用google搜索它回到$ q。 – venturz909
好吧,看看這個答案,例如http://stackoverflow.com/questions/19490560/angularjs-resource-promise或https://docs.angularjs.org/api/ngResource/service/$resource – user1665355