0

i've been trying to not use $scope when returning data from $http.get()

var app = angular.module('myApp',[])

app.controller('OrderCtrl',['$http',function($http){
    this.commande = null
    this.orders = {
        cde : null,
        start : '2014-01-01',
        end : '2014-01-31',
        get :  function(){
            return $http.get('http://apimucommerce/api/order/'+this.start+'/'+this.end+'/')
                .then(function(response){
                    return  response.data})
        }
    }

    this.commande = this.orders.get()
}])

the ajax call is returning datas, but i cannot assign to the this.commande property, what's wrong thanks.

Yvon Huynh
  • 453
  • 3
  • 16

1 Answers1

2

this.orders.get() returns a promise (from $http), not data. This is because it's asynchronous, and needs to fetch the data before it can return. The proper pattern for getting the data is:

var app = angular.module('myApp',[])

app.controller('OrderCtrl',['$http',function($http){
    var self = this;
    this.commande = null
    this.orders = {
        cde : null,
        start : '2014-01-01',
        end : '2014-01-31',
        get :  function(){
            return $http.get('http://apimucommerce/api/order/'+this.start+'/'+this.end+'/')
                .then(function(response){
                    return  response.data})
        }
    }

    this.orders.get().then(function(data){
      self.commande = data;
    })
}])
Dylan Watt
  • 3,357
  • 12
  • 16