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

标签 angularjs angularjs-ng-repeat

我有一个 Controller 和一个 Angular View 。 我正在通过 ajax 调用一个函数以从服务器获取数据,然后将其加载到数组中,然后将其与 ng-repeat 绑定(bind),它加载数据但不会显示,直到我单击任何按钮。 以下是代码。
查看。

<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>

Controller 。

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();

最佳答案

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

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

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

关于angularjs - ng-repeat 加载数据但在我单击某个按钮之前不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29771299/

相关文章:

javascript - 访问不同 ion-content 的 ng-model

javascript - 使用 ng-repeat 时如何仅更新特定行

javascript - Angular.js 在指令中更新 SVG 模板

jquery - 切换在 Angular ng-repeat 中无法正常工作

javascript - 如何从自定义指令获取链接href?

angularjs - 使用 angularjs 禁用复选框

javascript - 如何使用 ngAnimate 滑动 div 及其所有内容?

javascript - Angular list 模型取消选中也会删除日期

angularjs - 如何使用 ng-repeat 进行展平

angularjs - 用于在客户端和服务器端验证 AngularJS 表单的单一事实来源 (DRY)