2016-09-26 37 views
0

對於自定義表單驗證,我創建了指令並檢查輸入是否有效。 在某些情況下,可能有多個錯誤,我不想在html中編寫太多的ng-messsage語句。AngularJs:如何從JavaScript返回錯誤消息?

我是否希望在html中有一個地方,並且會從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()對於調試很有用,只需將輸出放在括號內即可。要查看輸出,通過打通調試工具:

  1. 右鍵點擊任意位置,點擊「檢查元素」
  2. 按F12

然後發現,上面寫着「控制檯」一節。您的代碼將輸出到那裏。

+0

我不在尋找控制檯日誌。我想在html中使用動態文本消息的一條通信消息語句。錯誤消息應該在angularjs中設置。 ex

{{text}}