【问题标题】:Custom Angular validator in TypeScriptTypeScript 中的自定义 Angular 验证器
【发布时间】:2015-08-30 05:09:46
【问题描述】:

我在 TypeScript 中创建了一个自定义角度表单验证器。在浏览器上一切正常,但打字稿在这一行抱怨“类型'IModelValidators'上不存在属性'compareTo'”: ngModel.$validators.compareTo = modelValue => (modelValue === scope.otherModelValue); 这是有道理的,因为我基本上是在创建一个名为“comparedTo”的新验证器,它并不存在,只是将它附加到模型上。这在 javascript 中是完全有效的,但由于 Typescript 是强类型的,所以不太喜欢它。有谁知道如何以打字稿安全的方式将我的“compareTo”验证添加到 ngModel.$validators?谢谢!

'use strict';

module App.Directives {

    export interface ILoZScope extends angular.IScope {
        otherModelValue: string;
    }

    export class CompareToDirective implements angular.IDirective {

        // Directive parameters.
        public restrict = 'A';
        public require = 'ngModel';
        public scope = { otherModelValue: '=compareTo' }

        // Constructor 
        public static $inject = ['$window'];
        constructor($window) {}

        // Link function
        public link(scope: ILoZScope, element: angular.IAugmentedJQuery, attrs: angular.IAttributes, ngModel: angular.INgModelController) {

            ngModel.$validators.compareTo = modelValue => (modelValue === scope.otherModelValue);

            scope.$watch('otherModelValue', () => { ngModel.$validate(); });
        }

        // Creates an instance of the compareToDirective class.
        public static factory(): angular.IDirectiveFactory {
            const directive = ($window: angular.IWindowService) => new CompareToDirective($window);
            directive.$inject = ['$window'];
            return directive;
        }

    }

    angular
        .module('app')
        .directive('compareTo', CompareToDirective.factory());

}

【问题讨论】:

    标签: angularjs typescript angular-directive


    【解决方案1】:

    如果您只是想跳过打字稿错误,只需创建一个自定义的确定类型文件并添加类似的内容。

    interface IModelValidators {
           comparedTo: any;
        }
    

    如果您想获得正确的智能感知,请在您的自定义 d.ts 文件中使用类似的内容。

    interface IModelValidators {
               comparedTo: (modelValue: any, viewValue: any) => boolean;
            }
    

    【讨论】:

      【解决方案2】:

      另一种解决方案是

      ngModel.$validators["compareTo"] =  (modelValue, viewValue) : boolean => {
           if(modelValue....) {
               return true
           }
           return false;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-07
        • 2018-05-23
        • 2018-01-26
        • 2018-07-28
        • 2020-07-14
        • 1970-01-01
        • 1970-01-01
        • 2019-01-08
        • 1970-01-01
        相关资源
        最近更新 更多