AngularJs ng-repeat еще не отображает данные http 200 response - PullRequest
0 голосов
/ 14 декабря 2018

Это для академического задания.Я впервые использую Angularjs и пытаюсь отобразить данные на веб-странице.На консоли Chrome я получаю http-код ответа 200, что означает, что я успешно получаю данные, но, похоже, они не отображаются.

groups.html:

<html>

    <head>
        <script src = "groups.js"></script>
    </head>
<body>
<div ng-app="myApp">
<div ng-controller="groupsCtrl">
    <div class="group-jumbotron">
        <h1 class="display-4">Champion's League Groups</h1>
        <p class="lead">The 2018–19 UEFA Champions League group stage began on 18 September and is scheduled to end on 12 December 2018. <br/>
            A total of 32 teams compete in the group stage to decide the 16 places in the knockout phase of the 2018–19 UEFA Champions League.</p>
        <hr class="my-1">
        <p>Information about each group can be seen below</p>
    </div>
     <div class="addGroup-Title">
        <h4 class="display-6">Groups:</h4>

          <table>
      <thead>
        <tr>
            <th>Group Letter</th>
            <th>Number of Teams</th>
            <th>Matches Played</th>
            <th>Top Goalscorer</th>
            <th>Top Assists</th>
            <th>Most Cards</th>
            <th>Total Points</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="group in leagueGroup">
            <td>{{group.groupLetter}}</td>
            <td>{{group.numberOfTeams}}</td>
            <td>{{group.totalMatchesPlayed}}</td>
            <td>{{group.topGoalscorer}}</td>
            <td>{{group.topAssists}}</td>
            <td>{{group.mostCards}}</td>
            <td>{{group.totalPoints}}</td>
        </tr>
      </tbody>
    </table>
     </div>
    <div class="addGroup-Title">
        <h4 class="display-6">Add a New Group:</h4>


    <form ng-show="showForm" ng-submit="submitNewGroupForm()" style="margin-left: 10px;margin-right: 10px" ng-model="newGroup">
            <div class="form-row">
                <div class="form-group col-md-3">
                    <label for="AddGroupLetter">Group Letter:</label>
                    <input type="text" ng-model="newGroup.groupLetter"class="form-control" id="AddGroupLetter" min="1" max="2" required>
                </div>
                <div class="form-group col-md-3">
                    <label for="AddnumTeams">Number of Teams:</label>
                    <input type="number" class="form-control" id="AddnumTeams" ng-model="newGroup.numberOfTeams" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="AddTotalMatches">Total Matches Played:</label>
                    <input type="number" class="form-control" id="AddTotalMatches" ng-model="newGroup.totalMatchesPlayed" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="AddTotalPoints">Total Points:</label>
                    <input type="number" class="form-control" id="AddTotalPoints" ng-model="newGroup.totalPoints" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-3">
                    <label for="AddTopGoalscorer">Top Goalscorer:</label>
                    <input type="text" class="form-control" id="AddTopGoalscorer" ng-model="newGroup.topGoalscorer" required>
                </div>
                <div class="form-group col-md-3">
                    <label for="AddTopAssists">Top Assists:</label>
                    <input type="text" class="form-control" id="AddTopAssists" ng-model="newGroup.topAssists" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="AddMostCards">Most Cards</label>
                    <input type="text" class="form-control" id="AddMostCards" ng-model="newGroup.mostCards" required>
                </div>
            </div>
            <button type="submit" class="btn btn-primary btn-lg">Create A Group</button>
        </form>
    </div>

    <div class="addGroup-Title">
        <h4 class="display-6">Delete a Group:</h4>

        <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="DeleteGroup">ID of Group</label>
                    <input type="text" class="form-control" id="DeleteGroup" ng-model="groupData.groupId" required>
                </div>
            </div>
            <button type="submit" class="btn btn-primary btn-lg">Delete A Group</button>

    </div>
    </div>
</div>
    </body>
</html>

groups.js:

    'use strict';

angular.module('myApp.groups', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/groups', {
        templateUrl: 'groups/groups.html',
        controller: 'groupsCtrl'
    });
}])

.controller('groupsCtrl', function ($scope, $http) {
    $scope.leagueGroup = [];
    $http.get('http://localhost:5000/api/v1/groups')
        .then(function (response) {
            $scope.leagueGroup = response.data;
        });

    $scope.submitNewGroupForm = function () {
        $scope.newGroup =
            {
                groupId: getgroupId(),
                groupLetter: $scope.newGroup.groupLetter,
                numberOfTeams: $scope.newGroup.numberOfTeams,
                totalMatchesPlayed: $scope.newGroup.totalMatchesPlayed,
                topGoalscorer: $scope.newGroup.topGoalscorer,
                topAssists: $scope.newGroup.topAssists,
                mostCards: $scope.newGroup.mostCards,
                totalPoints: $scope.newGroup.totalPoints
            };

        $http.post('http://localhost:5000/api/v1/groups', $scope.newGroup)
            .then(function (response) {
                $scope.response = response.data;
                  alert('Created new Group: ' + $scope.response.stadiumName);
            });
    };

    $http.delete('http://localhost:5000/api/v1/groups/'+ $scope.groupData.groupId)
                .then(function (response) {
                    $scope.response = response.data;
                });
    });
        function getgroupId() {
            return Math.floor((Math.random() * 9999) + 10);
        }

Пример данных:

groupId: 1
groupLetter: "A"
mostCards: "Marcos Rojo"
numberOfTeams: 4
topAssists: "Kevin De Bruyne"
topGoalscorer: "Cristiano Ronaldo"
totalMatchesPlayed: 6
totalPoints: 48

Ответ (Chrome Dev):

[  
   {  
      "groupId":1,
      "groupLetter":"A",
      "mostCards":"Marcos Rojo",
      "numberOfTeams":4,
      "topAssists":"Kevin De Bruyne",
      "topGoalscorer":"Cristiano Ronaldo",
      "totalMatchesPlayed":6,
      "totalPoints":48
   },
   {  
      "groupId":2,
      "groupLetter":"B",
      "mostCards":"Ander Herrera",
      "numberOfTeams":4,
      "topAssists":"Luka Modric",
      "topGoalscorer":"Sergio Aguero",
      "totalMatchesPlayed":6,
      "totalPoints":36
   },
   {  
      "groupId":3,
      "groupLetter":"C",
      "mostCards":"Sergio Ramos",
      "numberOfTeams":4,
      "topAssists":"Xavi",
      "topGoalscorer":"Lionel Messi",
      "totalMatchesPlayed":6,
      "totalPoints":50
   },
   {  
      "groupId":4,
      "groupLetter":"D",
      "mostCards":"Virgil Van Dijk",
      "numberOfTeams":4,
      "topAssists":"Neymar",
      "topGoalscorer":"Kylian MBappe",
      "totalMatchesPlayed":6,
      "totalPoints":32
   }
]

Ответы [ 3 ]

0 голосов
/ 14 декабря 2018

Кажется, имя вашего модуля неверно.Вы назвали его myApp.groups, но оно должно быть просто myApp.

angular.module('myApp.groups', ['ngRoute'])

Должно быть:

angular.module('myApp', ['ngRoute'])

Вы получаете какие-либо ошибки в консоли?

const data = [{
    "groupId": 1,
    "groupLetter": "A",
    "mostCards": "Marcos Rojo",
    "numberOfTeams": 4,
    "topAssists": "Kevin De Bruyne",
    "topGoalscorer": "Cristiano Ronaldo",
    "totalMatchesPlayed": 6,
    "totalPoints": 48
  },
  {
    "groupId": 2,
    "groupLetter": "B",
    "mostCards": "Ander Herrera",
    "numberOfTeams": 4,
    "topAssists": "Luka Modric",
    "topGoalscorer": "Sergio Aguero",
    "totalMatchesPlayed": 6,
    "totalPoints": 36
  },
  {
    "groupId": 3,
    "groupLetter": "C",
    "mostCards": "Sergio Ramos",
    "numberOfTeams": 4,
    "topAssists": "Xavi",
    "topGoalscorer": "Lionel Messi",
    "totalMatchesPlayed": 6,
    "totalPoints": 50
  },
  {
    "groupId": 4,
    "groupLetter": "D",
    "mostCards": "Virgil Van Dijk",
    "numberOfTeams": 4,
    "topAssists": "Neymar",
    "topGoalscorer": "Kylian MBappe",
    "totalMatchesPlayed": 6,
    "totalPoints": 32
  }
];

const app = angular.module('myApp',[]);

app
.controller('groupsCtrl', ['$scope', '$http', '$timeout', function($scope, $http, $timeout) {

  $timeout(1000)
    .then(function() {
      $scope.leagueGroup = data;
    });

}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<html>

<body>
  <div ng-app="myApp">
    <div ng-controller="groupsCtrl">

      <div class="addGroup-Title">
        <h4 class="display-6">Groups:</h4>

        <table>
          <thead>
            <tr>
              <th>Group Letter</th>
              <th>Number of Teams</th>
              <th>Matches Played</th>
              <th>Top Goalscorer</th>
              <th>Top Assists</th>
              <th>Most Cards</th>
              <th>Total Points</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="group in leagueGroup">
              <td>{{group.groupLetter}}</td>
              <td>{{group.numberOfTeams}}</td>
              <td>{{group.totalMatchesPlayed}}</td>
              <td>{{group.topGoalscorer}}</td>
              <td>{{group.topAssists}}</td>
              <td>{{group.mostCards}}</td>
              <td>{{group.totalPoints}}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</body>

</html>
0 голосов
/ 14 декабря 2018

После большого количества головных ударов это оказывается в моих группах. Я вызываю все мои методы, такие как http.get, в тех же функциях.Их нужно вызывать для отдельных функций, чтобы они не запускались при загрузке экрана.Как только я реорганизовал в отдельные функции отображаемые данные.

Спасибо за помощь всем

0 голосов
/ 14 декабря 2018

Вы сделали console.log с объектом ответа, чтобы убедиться, что это то, что вы ожидаете?

Сделайте это здесь:

.then(function (response) {
        console.log(response);
        $scope.leagueGroup = response.data;
        $scope.$apply();
    });

Вы пытались сделать $ scope. $ apply () после назначения данных?

Другой способ подтвердить правильность ваших данных - просто вставить тег <pre> в шаблон, чтобы подтвердить привязку данных, например: {{leagueGroup}}

...