AngularJS函数调用会丢失对象范围

时间:2016-03-13 13:04:06

标签: angularjs

我有一个带有查询参数的URL,如下所示。

http://somehost/page.html#/?param1=value1&param2=value2`

在JS文件中,我有一个控制器,它根据下面的代码定义一个函数,并进行http调用并将数据分配给$ 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(); 
}

我刚刚开始学习angularJS,不知道为什么$scope.empList在http块之外是未定义的。

1 个答案:

答案 0 :(得分:1)

您的HTTP请求是异步的。所以你需要这样做:

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 
}
相关问题