我試圖設置一個簡單的控制器,使用服務進行異步http調用。我爲我編寫的另一個控制器設置了非常相似的東西,但由於某種原因,這個控制器無法正常工作。這個console.log($ scope.art);在then()塊中的行輸出正確的數據,但是一旦它不在then()塊中,$ scope.art就是未定義的。爲什麼會這樣?我很困惑!
app.controller('FeedbackController', ['$scope','getArt', function($scope, getArt) {
var art = getArt();
art.then(function(result) {
$scope.art = result;
console.log($scope.art);
}, function(reason) {
$scope.error = reason;
});
console.log($scope.art);
}])
.factory('getArt', ['$http', '$q', function($http, $q) {
return function() {
var deferred = $q.defer();
$http.post("/php/getArt.php")
.success(function (response) {
if (response == "nope") {
deferred.reject("Whoopsie! Something seems to have gone wrong.");
} else {
deferred.resolve(response);
}
})
.error(function() {
deferred.reject("There seems to be an issue with your connection.");
});
return deferred.promise;
};
}]);
非常感謝!
哦,老天爺我是一個傻瓜的文章!這很有意義。謝謝! –
歡迎來到javascript&async @CarterScottDavis :) –