我有一个简单的校验,检查对正则表达式的输入:
.directive('test', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function ($scope, element, attrs, ctrl) {
ctrl.$setValidity('namePattern', true);
function checkValid(name) {
console.log('checkValid executed');
if (!name || ctrl.$pristine) {
ctrl.$setValidity('namePattern', true);
return name;
}
var test = /^[A-Za-z0-9_-]+$/;
ctrl.$setValidity('namePattern', test.test(name));
return name;
}
// called when value changes via code/controller
ctrl.$formatters.unshift(checkValid);
// called when value changes in input element
ctrl.$parsers.unshift(checkValid);
}
};
});
我想单元测试此指令,并具备以下条件:
function initState() {
angular.mock.module('app');
angular.mock.inject(function($compile, $rootScope, $timeout){
$scope = $rootScope.$new();
$rootScope.safeApply = function(cb) {
$timeout(function() {
$scope.$digest();
});
};
$scope.model = {
instanceName: ''
};
var tmpl = angular.element('<form name="form">' +
'<input ng-model="model.instanceName" name="instanceName" test>' +
'</form>'
);
element = $compile(tmpl)($scope);
$scope.$apply();
form = $scope.form;
});
}
beforeEach(initState);
但是,对模型的更改不会触发checkValid
。我已经试过直接设置属性型号:
it('should trigger a change resulting in an invalid state', function() {
$scope.model.instanceName = 'this is an invalid name';
$scope.$digest();
expect(form.instanceName.$valid).to.be.false;
});
以及与周围$modelValue
胡闹:
it('should trigger a change resulting in an invalid state', function() {
form.instanceName.$modelValue = 'this is an invalid name';
$scope.$digest();
expect(form.instanceName.$valid).to.be.false;
});
我也试图通过element.triggerHandler
触发input
事件。
如何触发模型更改以便checkValid
通过$formatters
运行?
通过引用形式名称和输入名称(这是通过使用角1.2.23)
道歉,如果upvote/accept是不可靠的 - SO的应用程序有问题。现在应该解决。谢谢! – SomeKittens 2014-10-22 17:07:32