2016-03-15 71 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。你嘗試過嗎?