从另一个函数访问函数的范围变量

时间:2016-09-16 06:26:19

标签: javascript angularjs function

我是angularjs的新手,我无法从另一个函数访问函数的范围变量。

第一个功能

$scope.getCustomer = function (customer_id) {


                        ABCServices.wts.customer.customerList({customerId:customer_id}).then(function (data) {

                            console.log("^^^^^ABC show^^^^^");
                            $scope.wtsdata = data;

                            console.log($scope.wtsdata);

                        });

                    };

所以我想在我的第二个函数中访问$scope.wtsdata。当我尝试访问它时,它给我一个未定义的错误。如何做到这一点?

第二个功能

$scope.selectCustomer = function (item) {

                    $scope.item = item;


                    if (item.length === 8) {

                        $scope.getCustomer(item);


                        console.log("Check"+$scope.wtsdata);

                    }

                };

2 个答案:

答案 0 :(得分:1)

你可以用两种方式做到这一点

(i)在这种情况下使用 $rootScope

(ii)如果两个函数属于相同的控制器,则声明$ scope变量,否则您可以使用 Services 在控制器之间共享变量,

 ABCServices.wts.customer.customerList({customerId:customer_id}).then(function (data) {
          console.log("^^^^^ABC show^^^^^");
          $rootScope.wtsdata = data;           
});

$scope.selectCustomer = function (item) {
     $scope.item = item;
     if (item.length === 8) {
     $scope.getCustomer(item);
     console.log("Check"+$rootScope.wtsdata);
   }
 };

答案 1 :(得分:0)

我已为您的问题制作了示例fiddle,我希望这会解决您的问题。下面是示例代码

angular.module('MainApp', [])
    .controller('Ctrl', function($scope, $timeout) {

        $scope.wtsdata = {}; //it can be array too then []
        $scope.selectCustomer = function(item) {
            $scope.item = item;
            if (item.length === 8) {
                $scope.getCustomer(item);
                console.log("Check" + $scope.wtsdata);
            }

        };

        $scope.getCustomer = function(customer_id) {

            $scope.wtsdata = 'Data fetched from service';
            /*ABCServices.wts.customer.customerList({
                customerId: customer_id
            }).then(function(data) {

                console.log("^^^^^ABC show^^^^^");
                $scope.wtsdata = data;

                console.log($scope.wtsdata);

            });*/

        };
    });
相关问题