2016-03-15 41 views
1

你能帮助我,请即时在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"]; 

})(); 

的信息:代码工作完全不同的是承诺,我要转换为synchonous如果你能帮助我,请。

预先感谢您

+0

你可以尝试'$ scope.users.concat.apply($ scope.users,响应);而不是'$ scope.users =响应';'? – dfsq

+0

另一种很好的解决方案是加载在服务中的数据,并注入该服务为您的控制器http://stackoverflow.com/questions/15161537/angularjs-load-data-from-service –

+0

我会注意到,我改变机(家用机器上班(在工作),它的工作原理没有改变任何东西),但非常感谢你的支持。我注意到,下一个数据加载 – AmenzO

回答

2

在大多数情况下,没有理由将任何数据保留在ng表的范围之外。我的建议是不修改或引用任何范围变量,因为这可能会导致很难跟踪时间问题。

看一看真正的好NG-表文档,它主要有你的使用情况工作示例。 See the docs here

根据您的过滤/排序发生的地方,你需要适应这一点,但应该基本上如下工作:

$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时,您的服务器响应。否则分页将不可见。

+0

非常感谢你的支持,我只是改变了机器,现在我的代码工作完美,但我注意到,明年开发者 谢谢你这么多 – AmenzO

+0

@AmenzO,你能然后标记ajaegle的答案是接受的答案?这就是它在stackoverflow :)上的工作方式。 – Bart

+0

谢谢bart的建议,最后一天我读了评论iwant使它得到了答案,但我没有找到ajaeagle在上下按钮:)再次谢谢:) – AmenzO

2

我认为这对增加$scope.usersTable给我你的承诺resolve方法中没有定义problema。你尝试过吗?