0

I'm new to angularjs and i have trouble accessing a scope variable of a function from another function.

1st function

$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);

                        });

                    };

So here i want to access $scope.wtsdata in my second function. When i try to access it it gives me a undefined error.How to do this?

2nd function

$scope.selectCustomer = function (item) {

                    $scope.item = item;


                    if (item.length === 8) {

                        $scope.getCustomer(item);


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

                    }

                };
Alpha Dog
  • 193
  • 1
  • 2
  • 6

2 Answers2

1

You can do it in two ways

(i)use $rootScope in this case

(ii) Declare the $scope variable outside if both functions belong to the same controller otherwise you can make use of Services to share the variable among controllers,

 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);
   }
 };
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

I have made sample fiddle for your problem,I hope this will resolve your issue.Below is the sample code

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);

            });*/

        };
    });
ngCoder
  • 2,095
  • 1
  • 13
  • 22