0

I'm sure this is probably easy, but I am messing up ajax calls here. I am pretty new to javascript so I don't really know what I'm doing wrong. I've tried to look it up online and can't get my calls to work at the correct time. Any help is really appreciated.

All i am trying to do is get NHL player data from a json to a table i created using angularjs. Right now the table is displayed when $scope.players is undefined, but once the ajax completes it has data. I am not displaying it at the right time, my table is always empty

RosterController related code:

(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 table code:

<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>
2
  • 1
    I'd recommend you to use the $http service that comes with AngularJS, or even Restangular. Also, could you please include a sample of the data? Commented Mar 7, 2016 at 2:53
  • so $scope.players is getting updated with the new values from the ajax request but the table is not updating? sounds like you need a $scope.apply() in your callback. the $http service will trigger the digest necessary on the callback. jquery doesnt Commented Mar 7, 2016 at 2:59

1 Answer 1

1

They way you're trying to implement it seems too much of the "JQuery way", which is very different from how angular works. First of all, avoid callbacks, use promises instead. Also, if it is an option, use $http or restangular instead.

An example of the service following my suggestions would be like this (the example is only for the fetchPlayers funcionality):

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 you can find a controller in a project that performs CRUD operations with $http and handles the response to show them in a table, and here is the implementation of the service to perform the calls to the backend API.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.