ng-повторите не связывающее событие, хотя я получаю данные

Простите меня, потому что я относительно новичок в AngularJS. У меня есть ситуация, когда я вызываю веб-сервис WebApi. У меня есть две страницы, одна, которая связывает, и одна, которая не связывает, с одним и тем же кодом в обоих. Я вижу, что веб-сервис попадает и возвращает данные. Есть идеи, в чем может быть проблема??

Это данные, возвращаемые webservice:

[{"id":1,"name":"Chester"  , "gender":"Male"   , "salary":25000},
     {"id":2,"name":"Mary" , "gender":"Female" , "salary":15000},
     {"id":3,"name":"Tim " , "gender":"Male"   , "salary":22000},
     {"id":8,"name":"Wayne", "gender":"Male"   , "salary":81231}]

Работает следующий код:

<!DOCTYPE html>
<html>

<head>
    <title></title>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/EmployeeAngular.js"></script>
    <meta charset="utf-8" />
</head>
<body ng-app="MyModule">
    <div ng-controller="MyController" ng-init="initController">
        {{MadeItHereMessage}}
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Gender</th>
                    <th>Salary</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="employee in employees">
                    <td>{{employee.id}}</td>
                    <td>{{employee.name}}</td>
                    <td>{{employee.gender}}</td>
                    <td>{{employee.salary}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

Код, который не работает здесь:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/EmployeeAngular.js"></script>
    <meta charset="utf-8" />
</head>
<body ng-app="EmployeeApplication">

<div ng-controller="EmployeeController" ng-init="AngularInit()">
        {{Message}}
    <br/>
        {{DisplayAction}}
    <br />
        <!--The following is for listing the entire list of employees-->
        <div id="listSection" ng-show="DisplayAction=='List'">
            <!--The employees data is: {{employees}}-->
    <!--<div id="listSection">-->
        <table>
            <thead>List of defined Employees</thead>
            <tr>
                <!--<td><button id="btnCreateNew" type="button" value="Create Employee" ng-click="CreateNewEmployee()"></button></td>-->
            </tr>
            <tr>
                <td ng-show="gotdata">

                    <table>
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Gender</th>
                                <th>Salary</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="employee in employees">
                                <td>{{employee.id}}</td>
                                <td>{{employee.name}}</td>
                                <td>{{employee.gender}}</td>
                                <td>{{employee.salary}}</td>
                            </tr>
                        </tbody>
                    </table>

                    <!--<table id="EmployeeList">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Gender</th>
                                <th>Salary</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="for employee in employees">
                                <td>{{employee.id}}</td>
                                <td>{{employee.name}}</td>
                                <td>{{employee.gender}}</td>
                                <td>{{employee.salary}}</td>
                                <td><button type="button" value="Details" ng-click="ShowDetails({{employee.id}})"></button></td>
                                <td><button type="button" value="Delete" ng-click="DeleteEmployee({{employee.id}})"></button></td>
                                <td><button type="button" value="Edit" ng-click="EditEmployee({{employee.id}})"></button></td>
                            </tr>
                        </tbody>
                    </table>-->
                </td>
            </tr>
        </table>
    </div>
        <!--The following is for listing the details of a single employee-->
        <!--<div id="DetailsSection" ng-show="DisplayAction=='Details'">
            <table>
                <tr>
                    <td>ID:</td>
                    <td> <input id="DetailsID" value={{id}} /></td>
                </tr>
                <tr>
                    <td>Name:</td>
                    <td><input id="DetailsName" value={{name}} /> </td>
                </tr>
                <tr>
                    <td>Gender:</td>
                    <td><input id="DetailsGender" value={{gender}} /> </td>
                </tr>
                <tr>
                    <td>Salary:</td>
                    <td><input id="DetailsSalary" value={{salary}} /> </td>
                </tr>
                <tr>
                    <td>
                        <button id="NavTolist" type="button" value="Back to List" ng-click="DisplayList()"></button>
                    </td>
                    <td>
                        <button id="NavToDelete" type="button" value="Delete" ng-click="DeleteEmployee({{id}})"></button>
                    </td>
                    <td>
                        <button id="NavToEdit" type="button" value="Edit" ng-click="EditEmployee({{id}})"></button>
                    </td>
                </tr>
            </table>
        </div>-->
        <!--The following is for editing a employee-->
        <!--<div id="EditSection" ng-show="DisplayAction=='Edit'">
            <table>
                <tr>
                    <td>ID:</td>
                    <td>
                        <input id="ID" value={{id}} />
                    </td>
                </tr>
                <tr>
                    <td>Name:</td>
                    <td><input id="" value={{name}} ng-bind="name" /> </td>
                </tr>
                <tr>
                    <td>Gender:</td>
                    <td><input id="" value={{gender}} ng-bind="gender" /> </td>
                </tr>
                <tr>
                    <td>Salary:</td>
                    <td><input id="" value={{salary}} ng-bind="salary" /> </td>
                </tr>
                <tr>
                    <td>
                        <button id="EditUpdate" type="button" value="Update" ng-click="EditUpdate()"></button>
                    </td>
                    <td>
                        <button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button>
                    </td>
                    <td>
                        <button id="NavToDeleteEdit" type="button" value="Delete" ng-click="DeleteEmployee({{id}})"></button>
                    </td>
                </tr>
            </table>
        </div>-->
        <!--The following is for verification of deletion-->
        <!--<div id="DeletionSection" ng-show="DisplayAction=='Delete'">
            <table>
                <tr>
                    <td>Do you really want to delete {{name}}</td>
                    <td></td>
                    <td>
                        <button id="btnCancelDelete" type="button" value="No"></button>
                    </td>
                    <td>
                        <button id="btnDeleteEmployee" type="button" value="Yes" ng-click="DoDeleteEmployee({{id}})"></button>
                    </td>
                </tr>
            </table>
        </div>-->
        <!--The following is for creation of a employee-->
        <!--<div id="CreationSection" ng-show="DisplayAction=='Create'">

            <table>
                <tr>
                    <td>Name:</td>
                    <td><input id="" value="" ng-bind="name" /> </td>
                </tr>
                <tr>
                    <td>Gender:</td>
                    <td><input id="" value="" ng-bind="gender" /> </td>
                </tr>
                <tr>
                    <td>Salary:</td>
                    <td><input id="" value="" ng-bind="salary" /> </td>
                </tr>
                <tr>
                    <td>
                        <button id="btnCreateEmployee" type="button" value="Delete" ng-click="CreateEmployee()"></button>
                    </td>
                    <td>
                        <button id="NavTolistEdit" type="button" value="Back to List" ng-click="DisplayList()"></button>
                    </td>
                </tr>
            </table>

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

Я получаю заголовок, но никаких фактических данных от веб-службы.

Файл angularjs javascript находится здесь:

    var app = angular.module("EmployeeApplication", [])
.controller("EmployeeController",

    function ($scope, $http) {

        AngularInit();

        function AngularInit()
        {
            //This will be called once per form load, via the ng-load function on the div
            $scope.name = '';
            $scope.gender = '';
            $scope.salary = '';
            $scope.id = '';
            $scope.DisplayAction = '';
            $scope.gotdata = false;
            DisplayList();
        }

        function GetAllEmployees($http) {
            //$scope.Message = 'NULL';
            //$scope.employees = {};
            $http.get('http://localhost:65315/api/employee').then(function (response) {
                $scope.employees = response.data;
                $scope.Message = 'OK';
                $scope.go = true;
            },
            function (err) {
                $scope.Message = 'Call failed' + err.status + '  ' + err.statusText;
                $scope.employees = {};
                $scope.gotdata = false;
            }
            );

            window.setTimeout(function () {
                $scope.gotdata = true;
            }, 1000);
        };

        function DisplayList() {
            //call the web service to get the list of people
            //set the display action so that the list will be displayed
            GetAllEmployees($http)
            $scope.DisplayAction = 'List';
        };

        function CreateNewEmployee() {
            $scope.name = '';
            $scope.gender = '';
            $scope.salary = '';
            $scope.id = '';
            $scope.DisplayAction = 'Create';
        };

        function ShowDetails(id) {
            //call the web service to get the details of the person
            //Set the $scope.CurrentEmployee
            $scope.DisplayAction = 'Details';
        };

        function CreateEmployee() {

            //perform the actual creation based on $scope.CurrentEmployee

            //if successful
            DisplayList();
        };

        function DeleteEmployee(id) {
            $scope.DisplayAction = 'Delete';
        };

        function DoDeleteEmployee(id) {
            //Perform actual deletion
            //if successful
            DisplayList();
        };

        function EditEmployee(id) {
            //get the employee based on ID
            $scope.DisplayAction = 'Edit';
        };

        function EditUpdate() {
            //perform the actual update based on $scope.id

            //if successful
            DisplayList();
        };
    }

);

var app = angular.module("MyModule", []).controller("MyController", function ($scope, $http)
{
    $scope.MadeItHereMessage = 'We made it to the controller (first controller)';
    $scope.employees = {};
    $http.get('http://localhost:65315/api/employee').then(function (response) {
        $scope.employees = response.data;
        $scope.Message = "OK";
    },
    function (err)
    {
        $scope.Message = "Call failed" + err.status + "  " + err.statusText;
    }
    );

});

3 ответа

  1. Шаблон загружается до получения данных http. Таким образом, решение заключается в отображении шаблона, когда ressource загружен ng-if.

    Можете попробовать:

    <tr ng-repeat="employee in employees" ng-if="employees && employees!={undefined}">
    
  2. Замените вызов на window.setTimeout$timeoutслужбу.

    //window.setTimeout(function () {
    //Use $timeout service
    $timeout(function() {
        $scope.gotdata = true;
    }, 1000);
    

    $timeoutСервис должным образом интегрирован с циклом дайджеста AngularJS. Изменения$scope, внесенные сsetTimeout, не сразу замечаются платформой AngularJS.

    Дополнительные сведения см. В разделе Справочник по API службы AngularJS $timeout

  3. Сначала вам не нужно передавать $http в вашу»GetAllEmployees» -функцию, потому что она уже есть!

    Во-вторых, я бы предложил использовать «$q», чтобы сохранить ответ в переменную. Проверьте это