Search code examples
angularjsangularjs-scopeangularjs-service

Set a return value to a scope vaiable in Angular.js


I'm new to anguar.js, I'm stuck with a problem. I need to set a variable with the return value from a service a and then access it outside the. Here is my code,

fetchService.store_closing_time($scope.currentStore.id, moment(new Date()).format('YYYY-MM-DD'))
      .then (result) ->
        $scope.changedStoreCloseTime = result.close_time
        console.log "############# display inside##########"
        console.log $scope.changedStoreCloseTime
      , (result) ->
        flash.error = result.error
      console.log "#############display outside ##########"
      console.log $scope.changedStoreCloseTime

The service returns the data, but i'm not able to access $scope.changedStoreCloseTime outside the success function. How do I access it ..?

My fetch service:

 store_closing_time: (id, date) ->
      def = $q.defer()
      $http.get('url').
        then (result) ->
          def.resolve(result.data)

        , (result) ->
          def.reject(result.data)
      def.promise

The data is returned as expected ..!

Thanks In Advance.


Solution

  • I'm a bit new to CoffeeScript, but it looks like you are trying to access the value before your service has returned anything.

    Since the operation is asynchronous, you have to use either promises or callbacks to do something once the value arrives.