我正在创建一个表单验证,由于需要验证的字段太多,它变得太丑陋了。我需要优化它。所以,我正在使用ng-required基于其他字段值创建任何字段。当用户在其中一个字段中插入值时,其余字段将失去所需的质量,表单将变为有效。所以,为此我创建了一个这样的表达式:
<input ng-model="field.one" ng-required="
!field.two &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
<input ng-model="field.two" ng-required="
!field.one &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
因此,我打算在控制器中移动所需的表达式,或者您认为应该移动它以优化和组织代码。我想将它封装在控制器内的一个函数中,但我没有成功。我试过这样的事情:
VIEW
<input ng-model="field.one" ng-required="myFunc(field.one)"/>
CTRL
$scope.myFunc = function(modelField){
anything I tried in this fn I didn't make it to work syncronized with
the field models, updating their models based on user interaction :)
}
拜托,是否有人有想法应该怎么做?感谢。
答案 0 :(得分:0)
我更喜欢一个范围变量,它绑定到所有输入字段的必需属性。并且在更改任何输入字段时切换此变量。
http://plnkr.co/edit/PVXVD9RKM8cMwCVjFA7c?p=preview
<input type="text" ng-change="onChange(userName1, 'name1')" name="name1" ng-model="userName1" ng-required="required">
<input type="text" ng-change="onChange(userName2, 'name2')" name="name2" ng-model="userName2" ng-required="required">
$scope.required = true;
$scope.userNames = [];
$scope.onChange = function(val, name) {
if (val) {
if ($scope.userNames.indexOf(name) == -1) {
$scope.userNames.push(name);
}
$scope.required = false;
} else {
if ($scope.userNames.indexOf(name) !== -1) {
$scope.userNames.splice($scope.userNames.indexOf(name), 1);
}
if ($scope.userNames.length === 0) {
$scope.required = true;
}
}
}