在ng-view

时间:2015-11-07 02:45:39

标签: javascript angularjs ng-repeat angular-routing ng-view

我正在尝试在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>

1 个答案:

答案 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而不是传入。

希望有所帮助。