为我的表单中提交的某些文件申请了必填项,但我的表单是使用自定义指令创建的,因此动态创建了Html。我正在使用ng-repeat,我需要在用户输入提交按钮时显示一些字段,但它显示所有字段都是必需的。
<div ng-repeat="item in items">
<input type=[item.name]>
</div>
<p ng-show="ErrorMsg">Error Message </p>
当我检查控制器逻辑时
Controller.js
$scope.ErrorMsg = false;
if(item.value == null){
$scope.ErrorMsg = true;
}
但它显示错误消息的所有字段。请建议我如何处理
提前致谢!
答案 0 :(得分:0)
我创建了一个关于angularjs动态表单验证的简单plunkr,请参考这里:http://plnkr.co/edit/7OJHKsJPoHNqeeStBtnh。
// Code goes here
var myApp = angular.module('myApp',[]);
myApp.controller('DemoController', ['$scope', function($scope) {
function setTouched(form) {
angular.forEach(form, function (value, key) {
if (!/^\$/.test(key)) {
form[key].$setTouched();
}
});
}
var config = [];
for (var i = 0; i < 10; i++) {
var item = {};
item.name = 'input' + i;
item.required = (i%2 === 0) ? true : false;
config[i] = item;
}
$scope.config = config;
$scope.save = function() {
if ($scope.testForm.$invalid) {
setTouched($scope.testForm);
}
}
}]);
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angularjs@1.3.6" data-semver="1.3.6" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.6/angular.min.js"></script>
<script data-require="ng-messages@*" data-semver="1.3.16" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular-messages.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="DemoController">
<form name="testForm" ng-submit="save()" novalidate>
<div ng-repeat="item in config">
<input type="text" name="{{item.name}}" ng-model="item.value"
ng-required="item.required" />
<div ng-messages="testForm[item.name].$error"
ng-if="testForm[item.name].$invalid && testForm[item.name].$touched">
<div ng-message="required">this is required</div>
</div>
</div>
<button type="submit">save</button>
</form>
</body>
</html>
希望这有助于:)