retrieve value in controller when service is called and return the value that we receive from service to controller

Controller.js

In contoller.js i have $scope.data.state which when has success from the service it should return state as $scope.data.state as booked but when i try to put alert in controller at the end of service i get the same state as self and not booked . I checked in the WEBAPI that i am using for performing the operation and i get success for booking . I am just wondering how to return a value . Help is very much appreciated .


$scope.data = {};
$scope.data.state = 'self';
$scope.data.starttime = new Date(new Date().getTime()).toLocaleTimeString();
$scope.data.endtime = new Date(new Date().getTime() + 8 * 60 * 60 * 1000).toLocaleTimeString();


myPopup = $ionicPopup.confirm({

    template: ' Enter Start Time <input type="time" id="exampleInput" name="input" ng-model="example.value" placeholder="HH:mm:ss" min="08:00:00" max="23:00:00" required /> <br> Enter End Time <input type="time" id="exampleInput1" name="input1" ng-model="example1.value" placeholder="HH:mm:ss" min="08:00:00" max="23:00:00" required /> ',
    title: 'WS' + settings.label,
    scope: $scope
});


//alert(time1);
NotifyingCache.put('SeatId', settings.label);
NotifyingCache.put('starttime', $scope.data.starttime);
NotifyingCache.put('endtime', $scope.data.endtime);

myPopup.then(function (res) {
    if (res) {
        NotifyingCache.put('starttime',document.getElementById("exampleInput").value);
        NotifyingCache.put('endtime',document.getElementById("exampleInput1").value);

        //alert(time1);
        var booking = {};
        var stat = '';
        booking.SeatId = NotifyingCache.get('SeatId');
        booking.UserId = NotifyingCache.get('UserId');
        booking.StartDate = new Date().toISOString().slice(0, 10);
        booking.EndDate = new Date().toISOString().slice(0, 10);
        booking.StartTime = NotifyingCache.get('starttime');
        booking.EndTime = NotifyingCache.get('endtime');
        BookingService.bookinguser(JSON.stringify(booking)).success(function (data) {
            var infoPopup = $ionicPopup.alert({
                title: 'Success',
                template: 'The desk has been successfully booked for you.'
            });
            $scope.data.state = 'booked';

        }).error(function (data) {

            var alertPopup = $ionicPopup.alert({
                title: 'Booking Failed!!!',
                template: data.Message
            });
            $scope.data.state = 'self';

        });
    } 

Services.js

ServiceModule.service('BookingService', function ($q, $http){

     return{

    bookinguser: function(user){

    //  alert(user);
            var config = {
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            }
            var deferred = $q.defer();
            var promise = deferred.promise;
            return $http.post('webAPI', user, config)
             .success(function (data, status, headers, config) {
                 deferred.resolve(data);
                 //return data;
             })
             .error(function (data, status, header, config) {
                 //alert(JSON.stringify(data));
                 var data =  "Data: " + data +
                     "<hr />status: " + status +
                     "<hr />headers: " + header +
                     "<hr />config: " + config;
                     deferred.reject(data);
             });
             promise.success = function (fn) {
                promise.then(fn);
                return promise;
            }
            promise.error = function (fn) {
                promise.then(null, fn);
                return promise;
            }
            return promise;
        }
    }
   });


ANSWERS:


I'll try a simil refactor without try the code. When you will try it probaably will find some typos or error.

Let's start with the service

ServiceModule.service('BookingService', function ($q, $http){

     return {
              bookinguser: bookinguser
            }

    function bookinguser(user){
      var config = {
          headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                    }
          }

          return $http.get('/api/maa')
                      .then(bookinguserComplete)
                      .catch(bookinguserFailed);


          function bookinguserComplete(response) {
              return response.data.results;
          }

          function bookinguserFailed(error) {
              var data =  "Data: " + data +
                "<hr />status: " + status +
                "<hr />headers: " + header +
                "<hr />config: " + config;
              logger.error(data);
          }
    }
});

So as I told you in the comment http already return promise so you can directly return from $http.post

As you can see in the service there is already a then and catch methods that pre elaborate your data but you still return a promise so you have to resolve it in the controller

Now the controller

.
.
.

booking.EndDate = new Date().toISOString().slice(0, 10);
booking.StartTime = NotifyingCache.get('starttime');
booking.EndTime = NotifyingCache.get('endtime');

BookingService.bookinguser(JSON.stringify(booking)).then(function (data) {
  var infoPopup = $ionicPopup.alert({
        title: 'Success',
        template: 'The desk has been successfully booked for you.'
    });
    $scope.data.state = 'booked';
  }).catch(function (data) {
    var alertPopup = $ionicPopup.alert({
        title: 'Booking Failed!!!',
        template: data.Message
    });
    $scope.data.state = 'self';

  });

Now I don't really know what your controller do but try with this structure and tell me what happen so I can try to help you more.

p.s. the refactor of dataservice is not my idea but is directly from this angular styleguide



 MORE:


 ? Should I have more angular services or controllers?
 ? Should I have more angular services or controllers?
 ? Should I have more angular services or controllers?
 ? AngularJS: controller vs service
 ? How to call a resource in a service through a controller in angularjs
 ? I can't inject service and constant in same controller?
 ? angular $controller locals substitue
 ? Service injection into controller having in seperate files with AngularJS
 ? angular Service calling twice
 ? How can I open an Angular Material menu from a controller function?