2014-07-22 49 views
1

我在發送到服務器之前需要計算我的角度模型中的屬性。我的控制器中有一個save()方法,它將模型發送到$ http服務以保存數據。它是這樣的:

$scope.user.customerId = lookup($scope.user.userId); 

其中lookup()查找本地數組中的值。 customerID值目前在視圖中根本不使用,但服務器需要customerID。

我的問題是:是否有計算值的最佳做法?

這應該在$ watch中隱式地在對象獲取器中完成,還是應該在保存時完成,無論是在控制器還是在服務中?還有其他的東西嗎?

我很欣賞任何輸入。

+0

通常你不計算之類的客戶ID的客戶端 - 它是由你的數據庫後端做服務器端,並通常會自動。一旦將對象添加到後端,您可以讀取結果(包含客戶ID),並在成功添加後將其分配給您的json對象。通常也許是 – pixelbits

+0

。然而,在這種情況下,我無法控制API。它發生了。 – user37078

回答

1

服務將是比控制器更好的選擇,因爲customerID將不會在視圖中使用。

但是如果customerID只有在服務器上使用,我推薦使用請求攔截器。你可以在official docs中閱讀更多關於它的信息。

希望這有助於:

module.factory('customerIdInterceptor', [function() { 
    var requestInterceptor = { 
    request: function(config) { 
     // request payload is in config.data 
     // calculate customerId and put it where you want it 
    } 
    }; 

    return requestInterceptor; 
}]); 

module.config(['$httpProvider', function($httpProvider) { 
    $httpProvider.interceptors.push('customerIdInterceptor'); 
}]);