需要进行哪些更改以获取下面的自定义countparens
指令,以便在表单验证期间提供下面显示的额外自定义字符串验证?以下代码在成功提醒用户时输入字段为空,但是当打开的parens (
和close parens )
的数量不相等时,它不会提醒用户。
我正在使用AngularJS。我使用the documentation at this link (scroll to bottom)来设计下面的代码。
以下是表单的html:
<table>
<tr>
<td width=200>
<form name="userForm" ng-submit="rectangularForm(userForm.$valid)" novalidate>
<input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required />
<p ng-show="userForm.fieldname.$invalid && !userForm.fieldname.$pristine" class="help-block">Function is a required field.</p>
<span ng-show="userForm.nameofjsontype.fieldname.$error.countparens">The #( != #) !</span>
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Click to submit</button>
</form>
</td>
</tr>
</table>
包含该指令的javascript文件包括:
// create angular app
var myApp = angular.module('myApp', []);
// create angular controller
myApp.controller('myController', ['$scope', '$http', function($scope, $http) {
$scope.nameofjsontype = {type:"nameofjsontype", fieldname: 'some (value) here.'};
$scope.rectangularForm = function(isValid) {
// check to make sure the form is completely valid
if (isValid) {
var funcJSON = {type:"nameofjsontype", fieldname: $scope.nameofjsontype.fieldname};
$http.post('/server/side/controller', funcJSON).then(function(response) {
$scope.nameofjsontype = response.data;
});
}
};
}]);
myApp.directive('countparens', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.countparens = function(modelValue, viewValue) {
if (ctrl.$isEmpty(modelValue)) {
// consider empty models to be valid
return true;
}
if (
($scope.nameofjsontype.fieldname.match(/\)/g).length) == ($scope.nameofjsontype.fieldname.match(/\(/g).length)
) {
// it is valid
return true;
}
// it is invalid
return false;
};
}
};
});
答案 0 :(得分:2)
您的标记应使用userForm.fieldname.$error.countparens
来显示错误。绑定到userForm
的字段与您的ngModel
值不同。请参阅plunker了解我的意思
<span ng-show="userForm.fieldname.$error.countparens" class="help-block">The #( != #) !</span>
您也没有在输入元素上使用您的指令:
<input type="text" name="fieldname" ng-model="nameofjsontype.fieldname" required data-countparens=""/>
在你的指令
中modelValue
而不是范围值
(
或)
myApp.directive('countparens', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.countparens = function(modelValue, viewValue) {
return ctrl.$isEmpty(modelValue) ||
((modelValue.match(/\)/g) || []).length == (modelValue.match(/\(/g) || []).length);
};
}
};
});