AngularJS & Typescript - Add a customised $validators

不羁岁月 提交于 2019-12-25 14:14:33

问题


I've created the following dummy directive with 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);
    }
  }

The directive gets used at the following location:

 <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>

The link function in the directive gets called and evaluates as I would expect but unfortunately the error message doesn't get displayed.

Is there any kind of way how I can troubleshoot this problem? With the tools I know, I am very limited.

来源:https://stackoverflow.com/questions/32333377/angularjs-typescript-add-a-customised-validators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!