我有一个 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/