1

I have a URL with query params as below.

http://somehost/page.html#/?param1=value1&param2=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.

1
  • $http.get() is asynchronous so your object is probably not populated by the time $scope.fetch() is called. Why don't you perform any additional logic inside your success function in $http.get()? Commented Mar 13, 2016 at 13:08

1 Answer 1

1

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 
}
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't seem to work as I need to use $scope.empList inside $scope.fetch.
$scope.fetch = function() { for (var i = 0; i <= $scope.empList.length; i++) { var emp1 = $scope.fetch[i]; if(emp1.key = "empName") { console.log("Name Exists") } } }
I've edited the answer. I guess, you have to set init value for $scope.empList = [] to make it works. And you have an error inside your loop: $scope.empList[i] instead of $scope.fetch[i]
Thanks alot Sir , It works very well. Truly appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.