简体   繁体   中英

AngularJS access $scope variable outside of the then callback

I invoke a method from my Bootstrap Modal submit button as below;

$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
};

Also this is how I invoke the addProject() in my views

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

I want to access the "response.data" which I set for $scope.dataList inside the then callback outside Currently it does not live update the grid with the above code.

How do I do that ?

***********Relevant grid code*********

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

You can't log directly the updated value of $scope.dataList because $http.post is a async function , but you really want to access it from outside the you need to invoke a function from success callback of $http.post Eg.

$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
    }
};

You can set a watcher for dataList outside of the callback. When the response.data returns, dataList is updated. Then the code in the watcher's callback will run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM