![](/img/trans.png)
[英]Why Nodejs callback() can't access variable outside callback 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.