Did not get value for
$scope.objectives.length
..... data to $scope.objectives
assigned at the time of page load....
it takes value from database...showing output like this
Asked
Active
Viewed 777 times
0

Groben
- 1,374
- 2
- 10
- 29

SUHAIL VALIYAPARAMBA
- 21
- 4
-
We dont get ya. – lin Feb 02 '17 at 08:04
-
Give `console.log` some time while `$http` request gets result. Its probably console logging before `http` result. – Hardik Vaghani Feb 02 '17 at 10:55
-
Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Feb 02 '17 at 12:04
2 Answers
1
http is asynchronus. it mean that the code executed in success or error will be after some time.
1) USE THEN for http, success is depreceated ! https://docs.angularjs.org/api/ng/service/$http
2)
when $http
is done, call a function who use the $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) another way is to set a watcher on $scope.objective
$scope.$watch('objective', function (newValue, oldValue, scope) {
console.log(newValue);
});

AlainIb
- 4,544
- 4
- 38
- 64
1
- 'Cannot read property length of undefined' error shows due to not initialization of $scope.objectives variable at first. So initialize this to empty array [] at top.
$http.get() is asynchronous function. This means the result or error will be obtained after the response status return back from the server after the succesfull HTTP request.
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); }]);

Jemesh Joseph
- 41
- 3