Use request data outside function?


#1

Hello I’m receiving a JSON object as a response, how do I use data outside the success function ? It says undefined when I do so.

    var request = $http({
        method: "post",
        url: "http://localhost:63342/myapp2/php/timings.php",
        data: {
            tid: tid
        },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });


    request.success(function (data) {
        **$scope.data = data;**

        $scope.timingsDisplay = function() {

            var timestring;

            var day = n.substring(0, 3);


            switch (day) {

                case "Mon":
                {
                    timestring = $scope.data[0].monday;
                    break;
                }
                case "Tue":
                {
                    timestring = $scope.data[0].tuesday;
                    break;
                }
                case "Wed":
                {
                    timestring = $scope.data[0].wednesday;
                    break;
                }
                case "Thu":
                {
                    timestring = $scope.data[0].thursday;
                    break;
                }
                case "Fri":
                {

                    timestring = $scope.data[0].friday;
                    break;
                }
                case "Sat":
                {
                    timestring = $scope.data[0].saturday;
                    break;
                }
                case "Sun":
                {
                    timestring = $scope.data[0].sunday;
                    break;
                }
            }
            $scope.timings1 = timestring.split(',');
            var notimestring = $scope.data[0].notimings;
            $scope.notimings1= notimestring.split(',');
            $scope.timings1 = _.difference($scope.timings1,$scope.notimings1);
            **return $scope.timings1;**
        };

        $scope.timingsDisplay();

    });

Some function (){
//how to use $scope.data here ?
}


#2

I’m assuming the success function is being called correctly. If thats the case, you should be able to use $scope.data everywhere as long as its in the same controller or service.

My guess is you are trying to use data before its initialized in that success function, so I’d make sure it is getting defined before you try referencing it.