2016-06-24 10 views
2

私はこれに関するすべての提案された投稿を読んだが、投稿後にフォームフィールドをクリアできないようだ。角度1.5 - 提出後のフォームをクリア

私はコントローラを構文として使用していますが、$ setPristineで$ scopeを使用しようとしても、まだ動作させることはできません。

これは私が従うものです。 https://stackoverflow.com/a/37234363/2062075 このコードをコピーしようとすると、何も起こりません。エラーはなく、何も消去されません。

は、ここに私のコードです:

app.controller('HiringRequestCtrl', function ($http) { 
    var vm = this; //empty object 
    vm.ctrl = {}; 

    vm.saveChanges = function() { 
     //console.log(vm); 
     $http({ 
      method: 'POST', 
      url: '/hiringrequest/createPost', 
      data: angular.toJson(vm) 
     }) 
      .success(function (response) { 
       //great, now reset the form 
       vm.ctrl = {}; 

      }) 
      .error(function (errorResponse) { 

      }); 

    } 
}); 

と私のフォームは次のようになります。

<div ng-controller="HiringRequestCtrl as ctrl"> 
<form id="form" name="ctrl.myForm"> 
... 

    <input type="text" name="proposalName" ng-model="ctrl.proposalName"/> 
    <input type="submit" id="saveButton" value="Submit" class="button" ng-click="ctrl.saveChanges()" /> 
    ... 

</form> 
</div> 

私は本当に$スコープを使用しないでしょう。

答えて

2

これを構成した方法にはいくつかの根本的な問題があります。私はvm.ctrlのあなたの使用を考えると、またng-controller="HiringRequestCtrl as ctrl"あなたを混乱させると思います。以下は私の推奨する[テストされていない]変更点です。 (.success().error()は非難されているので、のサービスをサービスに移動し、.then().catch()を使用することもお勧めします)。

コントローラ

.controller('HiringRequestCtrl', function($http) { 
    var vm = this; // self-referencing local variable required for when promise resolves 
    vm.model = {}; 

    vm.saveChanges = function() { 
     $http({ 
       method: 'POST', 
       url: '/hiringrequest/createPost', 
       data: angular.toJson(vm.model) 
      }) 
      .success(function(response) { 
       //great, now reset the form 
       vm.model = {}; // this resets the model 
       vm.myForm.$setPristine(); // this resets the form itself 
      }) 
      .error(function(errorResponse) {}); 
    } 
}); 

HTML

<div ng-controller="HiringRequestCtrl as ctrl"> 
    <form id="form" name="ctrl.myForm" ng-submit="ctrl.saveChanges()" novalidate> 
     <input type="text" name="proposalName" ng-model="ctrl.model.proposalName" /> 
     <input type="submit" id="saveButton" value="Submit" class="button" /> 
    </form> 
</div> 

更新
サービス

助けのためのの

コントローラ

.controller('HiringRequestCtrl', function(hiringService) { 
    vm.saveChanges = function() { 
     hiringService.createPost(model) 
      .then(function(response) { 
       // if you need to work with the returned data access using response.data 
       vm.model = {}; // this resets the model 
       vm.myForm.$setPristine(); // this resets the form itself 
      }) 
      .catch(function(error) { 
       // handle errors 
      }); 
    } 
+0

感謝。 Angularの基本的なレシピ(推奨されないもの、ベストプラクティスなどを含む)を得ることは本当に役に立ちました。ご協力いただきありがとうございます。 トピックオフ - $ httpをサービスに移行する方法を教えてください。 –

+0

サービスをどのように使用するかを示すために答えを更新しました。これにより、他のコントローラが利用できるようになり、モデルとビューのリンクにコントローラコードを集中させることができます。 – Lex

+0

簡潔でよく書かれています。もう一度レックスに感謝します。 –

関連する問題