簡體   English   中英

AngularJS在then回調之外訪問$ scope變量

[英]AngularJS access $scope variable outside of the then callback

我從Bootstrap Modal提交按鈕中調用一個方法,如下所示;

$scope.addProject = function() {
    $http.post('/cc-addProject' , $scope.project).then(function successCallback(response) {
        $('#myModal').modal('toggle'); 
        $scope.dataList = response.data;
      }, function errorCallback(response) {     
      });
    console.log("$scope.dataList : " + $scope.dataList); // I cannot access the same response.data here
};

這也是我在視圖中調用addProject()的方式

<button type="button" class="btn btn-info pull-right"  style="margin-left:10px;" ng-click="addProject()" ng-if="selectedID == -1">Sumbit</button>

我想訪問我為$ scope.dataList設置的“ response.data”,然后在外部的外部回調中使用。目前,它不使用上述代碼實時更新網格。

我怎么做 ?

***********相關網格代碼*********

<tbody>                             
    <tr role="row" class="odd" ng-repeat="project in dataList">
        <td>{{project.projectName}}</td>
    </tr>
</tbody>

您不能直接記錄$scope.dataList的更新值,因為$http.post是一個async function ,但是您確實想從外部訪問它,因此您需要從$http.post成功回調中調用一個函數。

$scope.addProject = function() {
    $http.post('/cc-addProject' , $scope.project).then(function successCallback(response) {
        $('#myModal').modal('toggle'); 
        $scope.dataList = response.data;
        useUpdatedValue();
      }, function errorCallback(response) {     
    });

    function useUpdatedValue() {
      console.log("$scope.dataList : " + $scope.dataList); // I cannot access the same response.data here
    }
};

您可以在回調之外為dataList設置觀察者。 當response.data返回時,dataList被更新。 然后,監視程序的回調中的代碼將運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM