我有从 JSON 动态生成的 html,我想实现一些验证逻辑。
为了澄清这一点,这里有一个例子:
<div ng-switch on="field.type" ng-hide="{{ field.hide }}">
<div ng-switch-when="input" class= "col-md-6" ng-class="{'has-error': reqField(field.name, entity[field.name]) }">
<input
ng-model="entity[field.name]" id="{{field.name}}" class="form-control"
type="text" ng-style="setStyle(field.style)" ng-change="{{field.change}}" />
</div>
</div>
<小时/>
{
"title": "Json Title",
"id": "j_id",
"groupfields": [
{
"name": "jsonname",
"title": "JSON Title",
"type": "jsonselect",
"namevalue": "jsonvalue",
"combo": "jsondropdown",
"change" : "jsonChanged()"
},
{
"name": "jsonEmail",
"title": "JSON Email Address",
"type": "display"
},
{
"name": "jsonPhone",
"title": "JSON Phone Number",
"type": "display"
}
]
}, {
"title": "Json Title",
"id": "j_id",
"groupfields": [
{
"name": "jsonname",
"title": "JSON Title",
"type": "jsonselect",
"namevalue": "jsonvalue",
"combo": "jsondropdown",
"change" : "jsonChanged()"
},
{
"name": "jsonEmail",
"title": "JSON Email Address",
"type": "display"
},
{
"name": "jsonPhone",
"title": "JSON Phone Number",
"type": "display"
}
]
},
<小时/>
if (entityName) {
return false;
} else {
return true;
}
<小时/>
因此,为了澄清,例如:ng-switch on 中的“field.type”是 JSON 中的“类型” - 我们可以根据不同的 JSON 键/值确定哪个 html div 显示内容。
这意味着一个 html div 可能会被用来生成数百个输入字段,因此这需要是动态的。
我想在必填字段为空时添加验证。目前,我尝试添加 ng-class="{has-error': }
它指向我的函数 reqField。然而,因为这个函数对于每个带有“type”的字段都会被触发:jsonselect,所以这个函数正在检查该字段是否为空 - 这在速度和可用性方面确实效率低下( super 滞后)。
您在上面看到的 javascript 或多或少是函数 reqField()
的逻辑。这样做是为了检查该字段是否为空(非常低效,因为我们要检查数百个)。
我想使用类似于 ng-required={{field.required}}
的东西并在 JSON 中创建一个新的键/值来确定我是否希望该字段成为必填字段(按如下方式排序):
{
"title": "Json Title",
"id": "j_id",
"groupfields": [
{
"name": "jsonname",
"title": "JSON Title",
"type": "jsonselect",
"namevalue": "jsonvalue",
"combo": "jsondropdown",
"change" : "jsonChanged()"
},
{
"name": "jsonEmail",
"title": "JSON Email Address",
"type": "display",
"required": true
},
{
"name": "jsonPhone",
"title": "JSON Phone Number",
"type": "display",
"required": true
}
]
},
~ 并以某种方式将该信息传递给 ng-class="{has-error': }
这样我们就可以突出显示 - 或者在知道该字段已填写/或为空时执行我们想要的任何操作。
最佳答案
表单验证内置于 AngularJS 中。 ng-required
指令会将错误状态添加到表单对象,以便您可以像这样设置 ng-class
:
<div ng-switch-when="input" class= "col-md-6" ng-class="{'has-error': myForm[field.name].$error.required }">
您的表单和输入必须具有 名称
属性才能正常工作:
<form name="myForm">
...
<input name="{{field.name}}" ng-required="field.required">
关于javascript - AngularJS:动态地将 has-error 应用于输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57478489/