2016-09-26 2 views
0

カスタムフォーム検証のために、私はディレクティブを作成し、入力が有効かどうかを確認しました。 いくつかのケースでは複数のエラーが発生する可能性があり、HTMLにあまりにも多くのng-messsageステートメントを書きたくありません。AngularJs:javascriptからエラーメッセージを返すには?

私はHTMLに1つの場所が必要かどうか、エラーはjavascriptから返されます。

function strongSecret() { 
     return { 
      restrict: 'A', 
      require: 'ngModel', 
      link: function (scope, element, attr, ctrl) { 

       // please note you can name your function & argument anything you like 
       function customValidator(ngModelValue) { 

        // check if contains uppercase 
        // if it does contain uppercase, set our custom `uppercaseValidator` to valid/true 
        // otherwise set it to non-valid/false 
        if (/[A-Z]/.test(ngModelValue)) { 
         ctrl.$setValidity('uppercaseValidator', true); 
        } else { 
         ctrl.$setValidity('uppercaseValidator', false); 
        } 

        // check if contains number 
        // if it does contain number, set our custom `numberValidator` to valid/true 
        // otherwise set it to non-valid/false 
        if (/[0-9]/.test(ngModelValue)) { 
         ctrl.$setValidity('numberValidator', true); 
        } else { 
         ctrl.$setValidity('numberValidator', false); 
        } 

        // check if the length of our input is exactly 6 characters 
        // if it is 6, set our custom `sixCharactersValidator` to valid/true 
        // othwise set it to non-valid/false 
        if (ngModelValue.length === 6) { 
         ctrl.$setValidity('sixCharactersValidator', true); 
        } else { 
         ctrl.$setValidity('sixCharactersValidator', false); 
        } 

        // we need to return our ngModelValue, to be displayed to the user(value of the input) 
        return ngModelValue; 
       } 

       // we need to add our customValidator function to an array of other(build-in or custom) functions 
       // I have not notice any performance issues, but it would be worth investigating how much 
       // effect does this have on the performance of the app 
       ctrl.$parsers.push(customValidator); 

      } 
     } 
    } 

私は何かのようなものを見ていますが、角度の特定のエラーのための任意のセットメッセージメソッドまたは同様のものがありますか?

答えて

0

console.log()を探している可能性があります。 console.log()はデバッグに便利です。出力をかっこ内に入れてください。で、デバッガツールを開き、出力を表示するには:右の任意の場所をクリックし

は次に「コンソール」と言うセクションを見つけ

  • F12キーを押して「要素を点検」をクリックします。あなたのコードはそこに出力されます。

  • +0

    私はコンソールログを探していません。私は、HTMLで動的テキストメッセージを持つ1つの通信文を作成したい。エラーメッセージがangularjsにセットされるはずです。 ex

    {{text}}

    関連する問題