2014-01-16 190 views
0
'use strict'; 

var app = angular.module('app'); 
app.factory('currTripService', function() { 
     var currtrip =''; 

    return{ 
     setCurrTrip: function(trip){ 
      currtrip = trip ; 
     }, 
     getCurrTrip: function(){ 
      return currtrip ; 
     }, 
    } 
}); 


app.controller('TripCreateController', function($scope, $location, Trip,currTripService) { 
    //The save method which is called when the user wants to submit their data 
    $scope.save = function() { 

     //Create the forum object to send to the back-end 
     var trip = new Trip($scope.trip); 
      console.log(trip); 
     currTripService.setCurrTrip(trip); 
     console.log(currTripService.getCurrTrip()); 
     //Save the forum object 
     trip.$save(function() { 
      //Redirect us back to the main page 
      $location.path('/trip/day/1'); 

     }, function(response) { 

      //Post response objects to the view 
      $scope.errors = response.data.errors; 
     }); 
    } 
}); 

app.controller('TripDayCreateController',function($scope,$routeParams,currTripService){ 
    $scope.items=[]; 
    $scope.trip = currTripService.getCurrTrip(); 
console.log($scope.trip.city); 

    // $scope.products = productService.getProducts(); 
    $scope.addItem = function(item) { 
       $scope.items.push(item); 
       $scope.item = {}; 
    } 
}); 

當我點擊/ trip/new時,它會在TripCreateController中保存並在currTripService中設置trip對象。 然後,當重定向到TripDayCreateContoller的的console.log(currTripService.getTrip()),返回 '不確定'角度js,傳遞服務對象

是因爲旅行是一個對象?我怎樣才能解決這個問題 ?

回答

1

試試這個:

app.factory('currTripService', function() { 
    var currtrip = ''; 
    var self = this; 
    return{ 
    setCurrTrip: function(trip){ 
     self.currtrip = trip ; 
    }, 
    getCurrTrip: function(){ 
     return self.currtrip ; 
    }, 
    } 
}); 

在聲明功能,this範圍變化如此之currtrip只存在於你的getter/setter函數,而不是外界。

+0

@harshit您可能還希望將所有持久性功能移出控制器並進入服務。 –

+0

是的,好點。 – harshit

1

做到這一點的最好方法是使用一個類。下面是一個來自CoffeeScript的類的例子。

class currTripService 

    # storage object 
    @data = null 

    # get data 
    get: => 
     return @data 

    # set data 
    put: (data) => 
     @data = data 

app.factory('currTripService', currTripService) 

但是,如果你想做到這一點沒有一個類的方法,那麼你可以改用東西會模仿類:

var currTripService = function() { 

    // storage variable 
    var currTrip = null 

    // reference to this element 
    var _this = this 

    return{ 
     // set this trip value 
     setCurrTrip: function(trip){ 
      _this.currtrip = trip; 
     }, 
     // get this trip value 
     getCurrTrip: function(){ 
      return _this.currtrip; 
     }, 
    } 
} 

app.factory('currTripService', currTripService); 

剛一說明:我把功能外廠模仿你通常如何調用一個類,但顯然你可以把所有的代碼放在函數聲明中。

app.factory('currTripService', function() { 

    // logic 

});