2017-12-18 102 views
0

在頁面加載時,我從數據庫中獲取數據並將其置於$scope.x中。在我的網絡選項卡中,我從我的數據庫中獲取列表,但它沒有加載到我將很快需要在下拉列表中使用ng-repeat的變量。但是,頁面加載後,當我單擊一個按鈕來檢索數據並將其放入$scope.x中時,我已經獲得了這些值。如果我這樣做,我沒有得到頁面加載的值,只需點擊檢索數據到變量的按鈕,我什麼都沒有。我究竟做錯了什麼。下面是我的代碼:來自數據庫的數據未使用角度加載到頁面加載時的變量

$scope.addProject = function() { 
    debugger; 
    console.log($scope.clientList); 
    console.log($scope.userList); 
}; 

$scope.getClients = function() { 
    debugger; 
    $http.get('/Clients/GetClients') 
     .then(function (response) { 
      $scope.clientList = response.data; 
     }); 
}; 

$scope.getAllUsers = function() { 
    debugger; 
    $http.get('/User/GetAllUsers') 
     .then(function (response) { 
      $scope.userList = response.data; 
     }) 
}; 

$scope.getClients(); 
$scope.getAllUsers(); 
$scope.addProject(); 

回答

3

數據從服務器返回之前addProject函數被調用的數據。

修改getClientsgetAllUsers函數返回的承諾:

$scope.addProject = function() { 
    debugger; 
    console.log($scope.clientList); 
    console.log($scope.userList); 
}; 

$scope.getClients = function() { 
    debugger; 
    ̲r̲e̲t̲u̲r̲n̲ $http.get('/Clients/GetClients') 
     .then(function (response) { 
      $scope.clientList = response.data; 
     }); 
}; 

$scope.getAllUsers = function() { 
    debugger; 
    ̲r̲e̲t̲u̲r̲n̲ $http.get('/User/GetAllUsers') 
     .then(function (response) { 
      $scope.userList = response.data; 
     }) 
}; 

然後使用$q.all等待承諾:

var clientsPromise = $scope.getClients(); 
var allUsersPromise = $scope.getAllUsers(); 

$q.all([clientsPromise, allUsersPromise]) 
    .then(function() { 
    $scope.addProject(); 
}); 
+0

angular.js:14642 ReferenceError:$ q沒有被定義是我得到的.. –

+0

'$ q'服務需要注入到控制器中,就像注入'$ http'服務一樣。 – georgeawg

+0

哇!這工作!你能解釋爲什麼它在我的原始代碼上不起作用嗎?爲什麼我們需要添加$ q.all或承諾? –

0

你應該得到這樣的

var getclients= function(){ 

    debugger; 
    console.log($scope.clientList); 
    console.log($scope.userList); 
}; 


getclients(); 
+0

我調用$ scope.getClients()和$範圍。 getAllUsers()在頁面加載已經。請檢查我的代碼,它位於代碼的底部。 –

+0

@stackquestions,而不是$ scope.getClients()你必須使用getClients()看到我的答案我清楚我調用範圍內變量。 – Vinoth

+0

現在,當我應用您的建議時,不會調用addProjects。請參閱我的更新代碼。 –

相關問題