AngularJS:访问函数外部函数

时间:2015-12-09 15:40:28

标签: angularjs

$scope.loadDistrict=function(id)
{

    $scope.districtList=[];
    angular.forEach($scope.districts,function(district, callback)
                    {
                        if(district.district_id==id)
                        {
                            $scope.districtList.push(district);
                            $scope.lat_wgs = district.lat_wgs;
                            $scope.long_wgs = district.long_wgs;
                            console.log($scope.lat_wgs);
                            console.log($scope.long_wgs);                  
                        }
                    })

};

您好,我是angular的新手。我的问题是我想在此函数外访问变量$scope.lat_wgs$scope.long_wgs。但是当我运行代码时,我得到了未定义。

1 个答案:

答案 0 :(得分:0)

您需要在函数

之前声明它们
$scope.lat_wgs = '';
$scope.long_wgs = '';
$scope.loadDistrict=function(id)
{
    $scope.districtList=[];
    angular.forEach($scope.districts,function(district, callback)
            {
                if(district.district_id==id)
                {
                    $scope.districtList.push(district);
                    $scope.lat_wgs = district.lat_wgs;
                    $scope.long_wgs = district.long_wgs;
                    console.log($scope.lat_wgs);
                    console.log($scope.long_wgs);                  
                }
            })
};

如果在{bracket}内声明变量,则此变量的值仅在此括号内知道。例如

foo = function(){
    var one = 1;
};
console.log(one); //oh no, i don't know what is value of 'one' variable
//well, I will output undefined

解决方案 - 在{bracket}

之前声明变量
var one = 1;
foo = function(){
    one = 2;
};
console.log(one); //it will output 2, cause value of variable 'one' changed 
//inside foo function, but it won't be undefined