2016-05-05 5 views
1

AngularJSでのカスタムフォームコントロールの検証に問題があります。AngularJSカスタムフォームでの制御の有効化

2つの問題がある:

  1. 私はプレースホルダ/初期テキストは、コンテンツの編集可能なフィールド内で変更されていないときにカスタムエラーをトリガします。私はさまざまなアプローチを試しましたが、運がない場合($isValidの編集を含む)解決

  2. 私はng-minlengthng-maxlength、およびng-requiredが無効であるときにそれらを表示させるために、エラーメッセージのng-showをトリガに見えることはできません。 (回答:私はdiv要素の名前attrのを持っていなかった)

以下Plnkrを参照してください、とコードサンプル:

https://plnkr.co/edit/Up6Q4D7cMDQQxCodLrpE?p=preview

<!doctype html> 
<html lang="en"> 

<head> 
    <meta charset="UTF-8"> 
    <title>Example - example-example40-production</title> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script> 
    <script src="script.js"></script> 
</head> 

<body ng-app="form-example2"> 
    <form name="myForm"> 
     <div contentEditable="true" ng-model="standfirst" title="Click to edit" ng-required="true" ng-minlength="5" ng-maxlength="20">Some People</div> 
     <p ng-show="myForm.standfirst.$error.required" class="text-danger">You did not enter a standfirst</p> 
     <p ng-show="myForm.standfirst.$error.minlength" class="text-danger">Your standfirst is too short</p> 
     <p ng-show="myForm.standfirst.$error.maxlength" class="text-danger">Your standfirst is too long</p> 
    </form> 
    <pre>model = {{content}}</pre> 

    <style type="text/css"> 
     div[contentEditable] { 
      cursor: pointer; 
      background-color: #D0D0D0; 
     } 
    </style> 
</body> 

</html> 
(function(angular) { 
    'use strict'; 
    angular.module('form-example2', []).directive('contenteditable', function() { 
     return { 
      require: 'ngModel', 
      link: function(scope, elm, attrs, ctrl) { 
       // view -> model 
       elm.on('blur', function() { 
        ctrl.$setViewValue(elm.html()); 
       }); 

       // model -> view 
       ctrl.$render = function() { 
        elm.html(ctrl.$viewValue); 
       }; 

       // load init value from DOM 
       ctrl.$setViewValue(elm.html()); 
      } 
     }; 
    }); 
})(window.angular); 
+0

フォームのどこにでも「standfirst」という名前の入力がありません。 – ryanyuyu

+0

また、この指令は何をする予定ですか?それは本当に明らかではありません。 – ryanyuyu

+0

@ryanyuyuこのディレクティブは、角度のあるドキュメンテーションのカスタムフォームコンポーネントの例からほんのほんのほんのほうであった。私はあなたのコメントの後に私の質問を修正しました –

答えて

1

$pristineを使用して、入力値が変更されているかどうかを確認できます。

<p ng-show="myForm.standfirst.$pristine" class="text-danger">Your start error message</p> 

ディレクティブで起動時に値を設定するため、フォームをリセットする必要があります。これを行うには、ctrl.$setPristine()をコードに追加してください。

// load init value from DOM 
ctrl.$setViewValue(elm.html()); 
ctrl.$setPristine(); 
+0

次に、私は '$ pristine'チェックを' submit-button'の 'ng-disabled'で使用しますか?無効な投稿を防ぐために.. –

+0

'$ valid'を使用すると、無効な投稿を防ぐことができます。しかし、変更のない送信を防ぐために '$ pristine'を使うことができます。私は常に 'ng-disable'属性の中でチェックを行いますが、submit関数の中で行うこともできます。 –

関連する問題