Reputation: 21
I have a URL with query params as below.
http://somehost/page.html#/?param1=value1¶m2=value2`
Inside the JS file I have a controller which defines a function as per the below code and makes a http call and assignes the data to the $scope.
angular.module('ngApp').controller('Cntrl', function ($scope,$location,$http){
var val1 = $location.search()['param1'];
$http.get('/api/call').success(function(data) {
$scope.empList = data;
console.log ($scope.empList) ; // return data
});
console.log ($scope.empList) ; // return undefined when accessed with above url
$scope.fetch = function() {
// some code which uses $scope.empList here
}
$scope.fetch();
}
I have just started to learn angularJS and no idea why $scope.empList
is undefined outside the http block.
Upvotes: 1
Views: 32
Reputation: 3765
Your HTTP request is asynchronous. So you need to do like this:
angular.module('ui.kpi.bugs').controller('BugKpiForm', function ($scope,$location,$http){
var val1 = $location.search()['param1'];
$scope.empList = [];
$http.get('/api/call').success(function(data) {
$scope.empList = data;
console.log ($scope.empList) ; // return data
$scope.fetch(); // invoke only when empList data is available.
});
$scope.fetch = function() {
// some code which uses $scope.empList here
}
Upvotes: 1