更新时间:2022-11-19 08:57:11
另一个答案的测试应写为:
The other answer's tests should be written as:
describe('directives', function() {
var $scope, form;
beforeEach(module('exampleDirective'));
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope;
var element = angular.element(
'<form name="form">' +
'<input ng-model="model.somenum" name="somenum" integer />' +
'</form>'
);
$scope.model = { somenum: null }
$compile(element)($scope);
form = $scope.form;
}));
describe('integer', function() {
it('should pass with integer', function() {
form.somenum.$setViewValue('3');
$scope.$digest();
expect($scope.model.somenum).toEqual('3');
expect(form.somenum.$valid).toBe(true);
});
it('should not pass with string', function() {
form.somenum.$setViewValue('a');
$scope.$digest();
expect($scope.model.somenum).toBeUndefined();
expect(form.somenum.$valid).toBe(false);
});
});
});
请注意,现在在$setViewValue
之后调用$scope.$digest()
.这样会将表单设置为脏"状态,否则将保持原始"状态,这可能不是您想要的.
Note that $scope.$digest()
now is invoked after $setViewValue
. This sets the form into "dirty" state, otherwise it would remain "pristine", which probably is not what you want.