我有一个带有查询参数的URL,如下所示。
http://somehost/page.html#/?param1=value1¶m2=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块之外是未定义的。
答案 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
}