javascript ajax没有按时更新变量

时间:2016-03-07 02:44:19

标签: javascript jquery angularjs ajax

我确定这可能很容易,但我在这里弄乱了ajax电话。我是javascript的新手,所以我不知道自己做错了什么。我试图在网上查找,但无法在正确的时间接听我的电话。任何帮助都非常感谢。

我想做的就是从json到我使用angularjs创建的桌子获取NHL播放器数据。现在,当$ scope.players未定义时,会显示该表,但是一旦ajax完成,它就会有数据。我没有在合适的时间展示它,我的桌子总是空的

RosterController相关代码:

(function () {
    'use strict';

    angular.module("DevilsFanApp")
        .controller("RosterController", RosterController);

    function RosterController($rootScope, $scope, RosterService) {
        $scope.players = RosterService.players;

        $scope.addPlayer = addPlayer;
        $scope.updatePlayer = updatePlayer;
        $scope.deletePlayer = deletePlayer;
        $scope.selectPlayer = selectPlayer;
        $scope.fetchPlayers = fetchPlayers;

        function init() {
            fetchPlayers(function(res){
                $scope.players = RosterService.players;
                console.log("Goalies Now", $scope.players);
            });
        }
        init();

        function fetchPlayers(callback) {
            var players = RosterService.updatePlayers(function(res){
                callback(players);
            });
        }   
    }
})();

RosterService:

function RosterService($rootScope) {
    var model = {
        players: [],
        updatePlayers: updatePlayers,
        setCurrentPlayer: setCurrentPlayer,
        getCurrentPlayer: getCurrentPlayer,
        findPlayerByName: findPlayerByName,
        findAllPlayers: findAllPlayers,
        createPlayer: createPlayer,
        deletePlayerById: deletePlayerById,
        updatePlayer: updatePlayer,
        findPlayerById: findPlayerById
    };
    return model;

    function updatePlayers(callback){
        $.ajax({
            url: URL,
            dataType: 'json',
            type: 'GET',
        }).done(function(response) {
            var data = angular.fromJson(response);
            for (var g = 0; g < data.goalie.length; g++) {
                var player = model.findPlayerByName(data.goalie[g].name);
                if (player == null) {
                    var newPlayer = {
                        _id: (new Date).getTime(),
                        name: data.goalie[g].name,
                        position: data.goalie[g].position,
                        height: data.goalie[g].height,
                        weight: data.goalie[g].weight,
                        birthday: data.goalie[g].birthdate,
                        age: 25,
                        birthPlace: data.goalie[g].birthplace,
                        number: data.goalie[g].number
                    };
                    model.players.push(newPlayer);
                }
                else{
                    callback(null)
                }
            }
            return callback(model.players)
        });
    }

RosterView表格代码:

<tr ng-repeat="player in players">
    <td>{{player.number}}</td>
    <td>{{player.name}}</td>
    <td>{{player.position}}</td>
    <td>{{player.height}}</td>
    <td>{{player.weight}}</td>
    <td>{{player.birthday}}</td>
    <td>{{player.age}}</td>
    <td>{{player.birthPlace}}</td>
    <td>
        <div class="col-sm-4 btn-group">
            <button ng-click="deletePlayer($index)" type="button" class="btn btn-table">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
            </button>
            <button ng-click="selectPlayer($index)" type="button" class="btn btn-table">
                <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
            </button>
        </div>
    </td>
</tr>

1 个答案:

答案 0 :(得分:1)

他们试图实现它的方式似乎太过于&#34; JQuery方式&#34;,这与角度工作方式有很大不同。首先,避免回调,改为使用promises。另外,如果是一个选项,请改用$httprestangular

遵循我的建议的服务示例如下(该示例仅适用于fetchPlayers功能):

angular.module('myModule', [])
.service('playersService', ['$http', function($http){
    this.fetchPlayers = function(){
        return $http.get(url);
    }
}])
.controller('playerCtrl', ['$scope', 'playersService', function($scope, playersService){
    $scope.players = []; //Start as an empty array
    this.fetchPlayers = function(){
        playersService.fetchPlayers.then(function(players){
            //here you can process the data as you need
            $scope.players = players; //assign to a property in scope so template can see it
        });
    };
    this.fetchPlayers(); //Invoke fetch on load
}])

Here您可以在项目中找到一个控制器,该控制器使用$ http执行CRUD操作并处理响应以在表中显示它们,here是执行调用的服务的实现到后端API。