Angular-material ng-messages中的自定义表单错误验证

时间:2016-06-21 06:41:42

标签: jquery angularjs angularjs-directive angular-material md-autocomplete

视图中的自动填充表单字段:

<md-autocomplete 
md-input-name="cityCode"
... 
md-floating-label="Enter city code" required cityCodeInvalid>

  <ng-messages="searchForm.cityCode.$error" ng-if="search.cityCode.$touched">
    <div ng-message="required">City Code required</div>
    <div ng-message="cityCodeInvalid">City code Invalid</div>
  </ng-messages>

</md-autocomplete>

JS代码

var app = angular.module('MyApp',['ngMaterial', 'ngMessages']);

/*
  My controller code: 
  app.controller.....
*/


app.directive('cityCodeInvalid', function() {
return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attributes, ngModel) {
        ngModel.$validators.cityCodeInvalid = function(modelValue) {
            console.log("In custom validate function");
            return true; /* forcibly returning true */

        }
    }
}
});

从上面的代码片段中,我正在尝试为md-autocomplete字段城市代码创建自定义错误消息。我有一系列城市代码,所以当用户故意输入一个不是我所拥有的代码列表的无效城市代码时,我想显示一条“无效城市代码”的ng消息

我看到我的代码无法正常工作,每次只是为了验证自定义函数(在指令中)是否已被触发,我强制从自定义验证函数返回true。我看不出结果。

1 个答案:

答案 0 :(得分:0)

搜索类似的错误。我认为Angular Directive应该放在元素“kebab-case”中。 指令camelCase:

app.directive('cityCodeInvalid', function()....

元素烤肉串案例:

<md-floating-label="Enter city code" required city-code-invalid>

我的回答是针对未来的人搜索类似错误并结束这个问题。