AngularJs:如何从javascript返回错误消息?

时间:2016-09-26 05:06:07

标签: javascript jquery angularjs html5

对于自定义表单验证,我创建了指令并检查输入是否有效。 在某些情况下,可能存在多个错误,我不想在html中写太多ng-messsage语句。

我是否希望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);

            }
      }
  }

我看起来像是,是否有任何set-message方法或类似的角度特定错误。

1 个答案:

答案 0 :(得分:0)

您可能正在寻找console.log()console.log()对调试很有用,只需将输出放在括号内。要查看输出,请通过以下方式打开调试器工具:

  1. 右键单击任意位置,单击“检查元素”
  2. 按F12
  3. 然后找到“控制台”部分。您的代码将输出到那里。