我有一条指令,该指令应用正则表达式清除文本输入中的任何值(例如Johnwww.
应该将模型值更新为John
)。
指令:
export default function ValidateSenderUsernameDirective():
IDirective<ValidateSenderUsernameDirectiveScope> {
return {
restrict: 'A',
scope: {},
require: 'ngModel',
link (scope: IScope, iElement: JQLite, iAttrs: IAttributes, ngModelCtrl: INgModelController): void {
function cleanInput (input: string): string {
if (!input) { return ''; }
const pattern: RegExp =
/[^A-Za-z0-9!@$*,./:=àâäèéêëîïôoeùûu^̈ÿçÀÂÄÈÉÊËÎÏÔOEÙÛÜŸÇ]|(https:|http:|www\.)/;
const validatedInput: string = input.replace(pattern, '');
if (input !== validatedInput) {
ngModelCtrl.$setViewValue(validatedInput);
ngModelCtrl.$render();
}
return validatedInput;
}
ngModelCtrl.$parsers.push((viewVal: string) => {
return cleanInput(viewVal);
});
}
};
}
测试:
describe('cleanInput', () => {
let scope: IDirectiveScope;
beforeEach(angular.mock.module(directiveModule));
beforeEach(angular.mock.inject(function($compile: ICompileService, $rootScope: IRootScopeService): void {
scope = $rootScope.$new() as IDirectiveScope;
const input: JQLite = $compile('<input type="text" ng-model="modelVal" validate-sender-username/>')(scope);
}));
it('should properly clean "Johnwww."', () => {
const result: string = 'John';
scope.modelVal = 'Johnwww.';
scope.$apply();
expect(scope.modelVal).toEqual(result);
});
});
为清楚起见,IDirectiveScope
扩展了IScope
,因为我需要定义modelVal
属性
export interface IDirectiveScope extends angular.IScope {
modelVal: string;
}
我收到错误Expected 'Johnwww.' to equal 'John'.
,scope.modelVal
在$scope.apply()
期间未更新。我在这里想念什么?