AngularJS&打字稿 - 添加自定义的$ validators

时间:2015-09-01 13:48:28

标签: angularjs validation angularjs-directive typescript

我使用typescript创建了以下伪指令:

 export class Room implements ng.IDirective{
    public restrict = 'A';
    public require = 'ngModel';

    public static DirectoryName = "room";

    public link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl : IRoomValidation) => {
      ctrl.$validators.room = function(modelValue, viewValue) {
        var ROOM_REGEXP = /^\w+$/;
        if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
        }

        if (ROOM_REGEXP.test(viewValue)) {
          // it is valid
          return true;
        }

        // it is invalid
        return false;
      };
    }

    public static factory(): ng.IDirectiveFactory {
      var directive = () => new Room();
      return directive;
    }
  }

interface IRoomValidation extends ng.INgModelController {
    $validators : {
      room(modelValue : string, viewValue : string);
    }
  }

该指令在以下位置使用:

 <form id="form" novalidate>
                  <label for="creation-name">Name:</label>
                  <input type="text" name="name" class="form-control" id="creation-name" ng-model="lobby.currentItem.name" room>
                  <span ng-show="form.name.$error.room">Only alphanumeric characters are accepted as input!</span>
                </form>

指令中的链接函数被调用并按照我的预期进行评估,但不幸的是错误消息没有显示出来。

enter image description here

有什么方法可以解决这个问题吗?借助我所知道的工具,我非常有限。

0 个答案:

没有答案