2014-06-16 38 views
1

我想POST數據從一個html表單到默認的動作url,但一個隱藏的輸入取決於從服務調用返回的數據。當我使用ng-submit時,在POST完成之前,$scope在服務呼叫之後沒有得到更新。我無法使用Ajax POST,因爲我在POST之後得到了一個HTML頁面。angularjs形式行動後服務電話

的形式如下:

<form name="payment" role="form" class="form-inline" ng-show="!loading" method="POST" action="{{paymentUrl}}" ng-submit="createOrder()" novalidate> 
    <input type="hidden" id="responseUrl" name="responseUrl" value="{{postPaymentUrl}}"/> 
    <input type="hidden" id="orderNumber" name="orderNumber" value="{{orderNumber}}"/> 
    <select class="form-control" id="paymentMethodBrand" name="paymentMethodBrand"> 
     <option ng-repeat="paymentMethod in paymentMethods | orderBy:'method'" value="{{paymentMethod.method}}">{{paymentMethod.method}}</option> 
    </select> 
    <button type="submit" class="btn btn-default" translate="BUY"></button> 
</form> 

action領域URL中獲取正確填寫。

控制器中createOrder功能是這樣的:

$scope.createOrder = function() { 
    Payment.start($scope.selectedProduct) 
    .then(function (response) { 
      $scope.orderNumber = response.data.orderNumber; 
    }); 
}; 

的問題是隱藏的輸入訂單號碼沒有得到開放的實際行動網址前填補。因此發佈的數據不正確。

有關如何解決這個問題的任何想法?我使用的是angularjs 1.2.16。

回答

3

問題是Payment.start在承諾的解決方案上異步設置$scope.orderNumber,但表單提交立即發生。通常,您可以通過在表單中​​省略action屬性來防止基於Angular的表單中的默認操作,因爲Angular是爲基於客戶端的應用程序設計的。但在你的情況下,你想要正常的http發佈,這是不尋常的。這讓我們在「最佳實踐」之外的旅行之旅。

因此,承認這是一個不尋常的用例,我將提供一個有點駭人聽聞的解決方案。你可以從表單中省略了action屬性,然後將其添加時的承諾從Payment.start解決,然後才觸發的形式提交:

$scope.createOrder = function() { 
    Payment.start($scope.selectedProduct) 
    .then(function (response) { 
      $scope.orderNumber = response.data.orderNumber; 
      var form = $('#form-id'); 
      form.attr('action', $scope.paymentUrl); 
      form.submit(); 
    }); 
}; 

這是未經測試,但我認爲它應該爲你工作。