$http.获取同步 AngularJS
$http.get to synchronous AngularJS
你能帮我吗,请我刚开始在angularJS,
我对异步 $http.get 有问题,我解释说:我得到了我在 ngTable 中显示的数据,但在我的 html 中我得到了一个空表,直到我单击过滤或排序然后我看到我的数据。
我想这是因为我的http.get中有一个承诺。 在这里,我的代码可以了解更多(对不起我的英语)
'use strict';
(function() {
angular
.module('timeShareApp')
.controller('homeController', homeController);
function homeController($http, $scope, $filter, NgTableParams) {
$scope.users =[];
$http.get('/api/users/').success(function(response) {
$scope.users = response;
});
$scope.usersTable = new NgTableParams({
page: 1,
count: 10
}, {
total: $scope.users.length,
getData: function ($defer, params) {
$scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
$scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
$scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.data);
}
});
}
homeController.$inject = ["$http", "$scope", "$filter", "NgTableParams"];
})();
对于信息:代码运行良好,除了那个承诺,如果你想帮我,我想转换为同步。
提前谢谢你
在大多数情况下,没有理由将任何数据保留在ng表的范围之外。我的建议是不要修改或引用任何范围变量,因为这可能会导致一些非常难以跟踪的时间问题。
看看真正好的ng-table文档,其中大部分都有适合您的用例的工作示例。在此处查看文档
根据过滤/排序发生的位置,您需要对此进行调整,但以下内容基本上应该有效:
$scope.loadData = function() { return $http.get('/api/users/') };
$scope.usersTable = new NgTableParams(
{
page: 1,
count: 10
}, {
total: 0, // just the inital value - will be updated later on
getData: function ($defer, params) {
$scope.loadData().success(function (result) {
// assuming your result has a total and a data field...
// update the table params with the total amount of results
// could also be result.length...
params.total(result.total);
// sort and filter your data using the params object here
var data = result.data;
// give back the control to the table
$defer.resolve(data);
});
}
}
);
请注意,每当服务器响应时,还要设置params.total
。否则,分页将不可见。
我认为在您的
承诺resolve
方法中向我添加$scope.usersTable
没有问题。你试过吗?
相关文章:
- angularjs文本区域-如何使其与angularjs下拉列表中的选定值保持同步
- AngularJS:在使用嵌套的JQuery Sortables时保持Dom和Model同步
- $resource 'get' 函数如何在 AngularJS 中同步工作
- 使用AngularJS,如何在视图和控制器同步特定更改后触发代码执行
- AngularJS.ng类与$scope中的变量不同步
- AngularJs:在内部调用$http或$resource时,让方法同步返回
- 如何确保angularjs app.js中的同步加载
- 模型绑定在 AngularJS 中不同步
- $http.获取同步 AngularJS
- AngularJS将实时收集与REST同步,并获得实时更新
- 使用LoDash和AngularJS进行实时同步更新
- AngularJS中的同步$resource
- AngularJs:$http同步调用
- 使用AngularJS同步两个数组中的数据
- angularJS:将重新排序列表与数据结构同步
- 同步与服务链接的两个AngularJS控制器
- 如何从angularjs同步调用json数据
- 用Angularjs同步Leafletjs的地图数据
- AngularJS:同步多个独立的承诺
- 在表单提交之前与AngularJS同步调用服务器