![](/img/trans.png)
[英]How to change a $scope variable outside the controller in angularjs
[英]How to get this AngularJS controller working ($scope variable not getting initialized in controller)?
var myApp = angular.module('myRealApp',[]);
myApp.controller('myController',function($scope,$http){
"use-strict";
$scope.content = [];
$scope.fetchContent = function () {
$http({
method : 'POST',
ContentType : "application/json",
url : "http://localhost:8080/myUrl",
headers : { 'Content-Type' : 'application/json'}
})
.success(function(response){
$scope.content = response;
console.log($scope.content); //Shows the returned object from server
});
}
$scope.fetchContent();
console.log($scope.content); //Shows as []
}
當我加載頁面時,$ scope.fetchContent被調用並從服務器獲取數據,還將其分配給$ scope.content。 但是,當我在此函數之外訪問$ scope.content時,它仍顯示其值為[]。 我在這里做什么錯?
從服務器返回的數據是對象列表。 (Java的ArrayList到JSON數組)。
$http
創建一個承諾,當對http://localhost:8080/myUrl
的ajax調用被解析時,該承諾將被解析。 當瀏覽器到達console.log($scope.content);
(在創建承諾后幾行)承諾尚未解決。
如果您想在.success()
之外解析承諾時做一些事情(例如console.log
),則必須獲取承諾並在$http
創建的承諾上使用.success()
.then()
如下所示:
"use-strict";
var myApp = angular.module('myRealApp',[]);
myApp.controller('myController',function($scope,$http){
$scope.content = [];
$scope.fetchContent = function () {
return $http({ //line changed
method : 'POST',
ContentType : "application/json",
url : "http://localhost:8080/myUrl",
headers : { 'Content-Type' : 'application/json'}
});
}
var promise = $scope.fetchContent();
promise.then(function() { //line changed
console.log($scope.content);
});
}
"use-strict";
文件頂部的行 myApp.controller('myController', function($scope,$http) { ... })
會在最小化Redondant版本時產生錯誤: myApp.controller('myController', ["$scope", "$http", function($scope,$http) { ... }])
$ http是異步的。 您的處理順序如下:
-> fetchContent()
-> console.log($scope.content) // outside of your $http
-> $http.success
無論如何,內容都會顯示在您的html模板中,因為angular正在監視您的范圍,所以不必擔心。 如果要在獲取數據后運行另一個進程,請在成功回調函數中調用該函數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.