我在TypeScript中创建了一个自定义角度形式验证器。一切都在浏览器上工作正常,但是打字稿抱怨说“此类线上的'IModelValidators''上不存在”属性'compareTo':
ngModel.$validators.compareTo = modelValue => (modelValue === scope.otherModelValue);
这是有道理的,因为我基本上创建了一个名为“comparativeTo”的新验证器,它不存在,只是将它附加到模型中。这在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());
}
答案 0 :(得分:1)
如果您只想跳过打字稿错误,只需创建一个自定义的明确类型文件并添加如下内容。
interface IModelValidators {
comparedTo: any;
}
如果你想获得正确的智能感知,请在你的自定义d.ts文件中使用这样的东西。
interface IModelValidators {
comparedTo: (modelValue: any, viewValue: any) => boolean;
}
答案 1 :(得分:1)
另一种解决方案是
ngModel.$validators["compareTo"] = (modelValue, viewValue) : boolean => {
if(modelValue....) {
return true
}
return false;
}