Функция AngularJs ng-click, получающая ошибку времени выполнения - не может прочитать свойство undefined - PullRequest
0 голосов
/ 15 декабря 2018

Привет! Я пытаюсь запустить функцию из моего файла .js с помощью кнопки, но когда я нажимаю кнопку, она не отвечает и ничего не происходит.

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 class="table">
            <thead class="thead-dark">
               <tr>
                  <th scope="col">Group Letter</th>
                  <th scope="col">Number of Teams</th>
                  <th scope="col">Matches Played</th>
                  <th scope="col">Top Goalscorer</th>
                  <th scope="col">Top Assists</th>
                  <th scope="col">Most Cards</th>
                  <th scope="col">Total Points</th>
                  <th scope="col"></th>
                  <th scope="col"></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>
                  <td><button type="submit" class="btn btn-outline-info" ng-click="getSpecificGroup()">Edit</button></td>
                  //THIS BUTTON                
                  <td><button type="button" class="btn btn-outline-danger" 
                     ng-click="deleteGroupById()">Delete</button></td>
               </tr>
            </tbody>
         </table>
      </div>

.js file:

'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.deleteGroupById = function () {
      const isConfirmed = window.confirm('Are you sure you want to delete Group: ' + $scope.groupData.groupId + '?');

      if (isConfirmed) {
        $http.get('http://localhost:5000/api/v1/groups/' + $scope.leagueGroup.groupId)
          .then(function (response) {
            $scope.groupData = response.data;
          });
        $http.delete('http://localhost:5000/api/v1/groups/' + $scope.groupData.groupId)
          .then(function (response) {
              $scope.response = response.data;
              alert('Group deleted successfully: ' + $scope.groupData.groupId);
            },
            function (error) {
              alert("Error! Group could not be deleted!" + $scope.groupData.groupId);
            });
      }
    };
  });

function getgroupId() {
  return Math.floor((Math.random() * 9999) + 10);
}

Chrome Inspector:

TypeError: Cannot read property 'groupId' of undefined
at b.$scope.deleteGroupById (groups.js:74)
at fn (eval at compile (angular.js:16387), <anonymous>:4:165)
at e (angular.js:28815)
at b.$eval (angular.js:19356)
at b.$apply (angular.js:19455)
at HTMLButtonElement.<anonymous> (angular.js:28819)
at og (angular.js:3805)
at HTMLButtonElement.d (angular.js:3793)

Так что он должен вызывать $ scope.deleteGroupById (), но, к сожалению, он просто ничего не делает ??Я использовал кнопки, используемые кнопки отправки, которые работают, а также пытался разместить кнопку за пределами таблицы, но она по-прежнему не отвечает

У кого-нибудь есть идеи?

1 Ответ

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

Когда вы используете ng-repeat, вы должны отправить информацию о праве на ваш function, чтобы контроллер увидел, какую информацию о праве использовать.Другая ошибка заключается в том, что вы пытались получить доступ к своему ответу до того, как $http завершит запрос.

 <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>
            <td><button type="submit" class="btn btn-outline-info" ng-click="getSpecificGroup(group)">Edit</button></td> <!-- Send the group to function -->
//THIS BUTTON                
<td><button type="button" class="btn btn-outline-danger" 
ng-click="deleteGroupById(group)">Delete</button></td> <!-- Send the group to function -->
        </tr>

И JS

// Width group parameter
$scope.deleteGroupById = function (group) {
    const isConfirmed = window.confirm('Are you sure you want to delete Group: ' + group.groupId + '?');

    if (isConfirmed) {
        $http.get('http://localhost:5000/api/v1/groups/' + group.groupId)
            .then(function (response) {
                $scope.groupData = response.data;

                // Delete when you get your response
                $http.delete('http://localhost:5000/api/v1/groups/' + $scope.groupData.groupId)
                    .then(function (response) {
                            $scope.response = response.data;
                            alert('Group deleted successfully: ' + $scope.groupData.groupId);
                        },
                        function (error) {
                            alert("Error! Group could not be deleted!" + $scope.groupData.groupId);
                        });
            });

    }
};
...