Angular: невозможно прочитать свойство 'id' из неопределенного

Я пытаюсь получить список игроков для загрузки, пока пользователь выбирает игру, однако я получаю Не могу прочитать свойство 'id' из undefined на m. $ Scope.getPlayers (campaigns-Players.js: 104)

Я использовал аналогичное на другой странице, но на этой странице появляется ошибка, так что я не совсем уверен, что сделал на этот раз неправильно. Ценю помощь!

HTML;

<div class="card-body">
                    <div class="form-group">
                        <label class="col-md-3 col-form-label">List of Games</label>
                        <select class="form-control" id="gameList" ng-model="game" ng-change="getPlayers()">
                            <option ng-repeat="game in allGames" ng-value="{{game.id}}"> {{game.name}}</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="name">List of Players</label>
                        <select class="form-control" id="ccmonth" ng-model="selectedPlayer">
                            <option ng-repeat="player in players" ng-value="{{player.id}}"> {{player.name}}</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="col-md-3 col-form-label">Player Name</label>
                        <input type="text" class="form-control" id="entityNameUpdate" ng-model="entityNameUpdate">
                    </div>
                    <div class="form-group">
                        <label for="name">Which game player in?</label>
                        <select class="form-control" id="updatedGamePlayer" ng-model="updatedGame">
                            <option ng-repeat="updatedGame in allGames" ng-value="{{updatedGame.id}}"> {{updatedGame.name}}</option>
                        </select>
                    </div>
                    <div class="col-sm-4">
                        <button type="submit" class="btn btn-sm btn-primary" ng-click="save()"><i class="fa fa-dot-circle-o"></i>
                            Save</button>
                    </div>

Файл JS

//main.js
angular
    .module('app', ['multipleSelect', 'ngSanitize'])
    .controller('adspacesController', adspacesController)
//, [multipleSelect]
//convert Hex to RGBA
adspacesController.$inject = ['$scope', '$http', '$location', '$timeout'];

function adspacesController($scope, $http, $location, $timeout) {
    var apiUrl = adminService;
    var token = window.localStorage.getItem('token');
    var config = {
        headers: {
            "Authorization": "" + "0481383f",
            "Accept": "application/json;charset=UTF-8",
            "Access-Control-Allow-Origin": "*",
            "contentType": 'application/json',
        }
    };

    $scope.getAllGames = function () {
        var url = apiUrl+"/game/all";
        $http.get(url, config)
            .then(function (response) {
                    if (response.data) {
                        debugger;
                        $scope.allGames = response.data;
                    } else {
                        $scope.showErrorMessage("No data found");
                    }
                },
                function (error) {
                    $scope.responseErrorCheck(error);
                }
            );
    };

    $scope.getPlayers = function () {
        debugger;
        var url = apiUrl + "/game/" + $scope.game.id;
        $http.get(url, config)
            .then(function (response) {
                debugger;
                    if (response.data) {
                        $scope.adspaces = response.data;
                    } else {
                        $scope.showErrorMessage("Player not found");
                    }
                },
                function (error) {
                    $scope.responseErrorCheck(error);
                }
            );
    };

    $scope.pageLoading = function (name) {
        $scope.getRules();
        $scope.getCategories();
        $scope.getAllGames();
        $scope.assetImageShow = false;
        $scope.game=''

    }

Всего 2 ответа


Решение 1

HTML:

<select class="form-control" id="gameList" ng-model="game" ng-change="getPlayers()">
<option ng-repeat="game in allGames" ng-value="{{game.id}}"> {{game.name}}</option>
</select>

В getPlayers ()

var url = apiUrl + "/game/" + $scope.game;

Решение 2 :

HTML:

<select class="form-control" id="gameList" ng-model="game" ng-change="getPlayers()">
<option ng-repeat="game in allGames" ng-value="{{game}}"> {{game.name}}</option>
</select>

В getPlayers ()

var url = apiUrl + "/game/" + $scope.game.id;

Запустите следующий фрагмент

  angular
    .module('myapp',[])
    .controller('ctrl', function($scope){
     $scope.game;
     $scope.allGames=[
     {
       name:"GTA",
       id:1
     },
     {
      name:"PUBG",
       id:2
     }
     ];
     $scope.getPlayers= function () {
        var url = "apiUrl/game/" + $scope.game.id;
        console.log(url);
    }});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="myapp" class="card-body">
    <div ng-controller="ctrl" class="form-group">
        <label class="col-md-3 col-form-label">List of Games</label>
        <select class="form-control" id="gameList" ng-model="game" ng-change="getPlayers()">
        <option ng-repeat="game in allGames" ng-value="game"> {{game.name}}</option>
        </select>
</div>
</div>


Измените значение ng здесь из игры в game.id

<div class="card-body">
    <div class="form-group">
        <label class="col-md-3 col-form-label">List of Games</label>
        <select class="form-control" id="gameList" ng-model="game" ng-change="getPlayers()">
        <option ng-repeat="game in allGames" ng-value="{{game.id}}"> {{game.name}}</option>
        </select>
</div>

В js-коде определите $ scope.game;

$scope.game;
 $scope.getPlayers = function () {
        var url = apiUrl + "/game/" + $scope.game.id;
        $http.get(url, config)
            .then(function (response) {
                    if (response.data) {
                        $scope.players = response.data;
                    } else {
                        $scope.showErrorMessage("Player not found");
                    }
                },
                function (error) {
                    $scope.responseErrorCheck(error);
                }
            );
    };

Есть идеи?

10000