答案 0 :(得分:0)
http是异步的。这意味着成功或错误执行的代码将在一段时间后。
1)用于http,成功被贬低! https://docs.angularjs.org/api/ng/service/ $ HTTP
2)
完成$http
后,调用使用$scope.objective
的函数:
$http({
method: 'GET',
url: '/getObjective'
}).then(function successCallback(response) {
console.log("test1"); // this will printed after test2 because http is asynchronus
$scope.objective = doc ;
anotherFunction();
}, function errorCallback(response) {
});
console.log("test2");
var anotherFunction = function(){
console.log($scope.objective.length);
}
3)另一种方法是在$scope.objective
$scope.$watch('objective', function (newValue, oldValue, scope) {
console.log(newValue);
});
答案 1 :(得分:0)
$ http.get()是异步函数。这意味着在成功的HTTP请求之后从服务器返回响应状态后,将获得结果或错误。
var myApp = angular.module('routingApp');
myApp.controller('objectiveController', ['$scope', '$http',
function($scope, $http) {
$scope.objectives = [];
$http.get('/getObjective').success(function (doc) {
$scope.objectives = doc;
//gets the actual length of result array
console.log($scope.objectives.length);
}).error(function (error) {
console.log('error');
});
//get the result 0
console.log($scope.objectives.length);
}]);