2016-09-26 45 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}}