ng-repeat加载数据,但在我点击某个按钮之前不会显示

Roh*_*pat 2 angularjs angularjs-ng-repeat

我有一个控制器和角度的视图.我通过ajax调用一个函数从服务器获取数据然后将其加载到数组中,然后用ng-repeat绑定它,它加载数据但不会显示,直到我点击任何按钮.以下是代码.
视图.

<table class="table table-striped" >
<thead>
    <tr>
        <th>Employee ID</th>
        <th>Name</th>
        <th>Designation</th>
        <th>Mobile No</th>
    </tr>
</thead>
<tbody>
    <tr data-ng-repeat="item in emplist">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.designation}}</td>
        <td>{{item.mobile}}</td>
    </tr>

</tbody></table>
Run Code Online (Sandbox Code Playgroud)

控制器.

angular
.module('MyApp.ctrl.crud', [])
.controller('loginController',[
    '$scope',

    function ($scope) {

        $scope.emplist = [];

        $scope.load = function () {
            $.ajax({
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                url: '/Home/getList',
                success: function (data) {
                    $scope.emplist = data;
                    console.log($scope.emplist);
                }
            });
        }

        $scope.load();
Run Code Online (Sandbox Code Playgroud)

小智 5

您应该尝试使用角度为$ j的ajax服务.如果这样做,您将不需要显式执行$ scope.load()之类的操作.这可能会发生,因为只有在用户操作之后才会刷新范围,并且只有它具有新的范围值.但是在$ http的情况下,当获取响应并将其存储在$ scope中时,作用域会自动刷新.

或者,如果您不想将代码更改为$ http,那么在成功回调$ .ajax时执行$ scope.$ apply()如下所示:

        success: function (data) {
            $scope.emplist = data;
            $scope.$apply();  // or $scope.$digest();
            console.log($scope.emplist);
        }
Run Code Online (Sandbox Code Playgroud)