我正在尝试在ng-view中使用ng-repeat,但它并没有提取数据。我正在论坛上阅读我可以使用工厂,但我不认为使用服务是可以接受的,因为我的$ scope的数据使用$ routeParams来查询它的数据。
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/:name', {
templateUrl: 'welcome.html',
controller: 'myController'
}).
otherwise ({
redirectTo: '/'
});
}]);
myApp.controller('myController', ['$scope', '$routeParams', '$q', function($scope, $routeParams, $q) {
var pls = users($q, $routeParams.name);
$scope.sBP = pls;
}]);
function users($q, name) {
var playersDFD = $q.defer();
var players = new Array();
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", name);
query.find({
success: function (results) {
for (var i in results) {
sPlayer = new player(results[i].get("playerName"), results[i].get("score"), results[i].get("cheatMode"));
players.push(sPlayer);
}
playersDFD.resolve(players);
},
error: function (error) {
alert('error');
playersDFD.reject(data);
}
});
return playersDFD.promise
.then(function (results) {
return results;
})
.catch(function (error) {
alert(error.message);
});
};
function player(name, score, cheatm){
this.name = name;
this.score = score;
this.cheatm = cheatm;
};
观点:
<p ng-repeat="s in sBP">
{{ s.name }}
</p>
答案 0 :(得分:1)
让你的users
函数返回承诺而不是尝试解决它,这最终会得到更容易理解的代码,并且会让user
函数的使用者控制什么到一旦收到回复,请做一下。例如。
function users($q, name) {
var playersDFD = $q.defer();
var players = new Array();
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", name);
query.find({
success: function (results) {
for (var i in results) {
sPlayer = new player(results[i].get("playerName"), results[i].get("score"), results[i].get("cheatMode"));
players.push(sPlayer);
}
playersDFD.resolve(players);
},
error: function (error) {
alert('error');
playersDFD.reject(data);
}
});
return playersDFD.promise;
}
然后使用users
函数并处理then
本身。
users($q, $routeParams.name).then(function (response) {
$scope.sBP = response;
}, function (error) {
// handle error.
});
另外,我建议将users
分成自己的service
以注入$q
而不是传入。
希望有所帮助。