我有以下ngRepeat代码:
<div ng-repeat="drug in drugs | orderBy:'drugName'">
<input id="{{drug.drugName}}"
class="drugCheckbox"
name="{{drug.drugName}}"
type="checkbox" value="{{drug.drugName}}"
ng-model="foobar"
validate-foo
/>
{{drug.drugName}}
<!-- this is the error message, one per each repeat element -->
<span style="color:red" ng-show="myForm.{{drug.drugName}}.$error.summary">
Fill in the summary
</span>
<input type="text"
name="summary-{{drug.drugName}}"
id="summary-{{drug.drugName}}"
placeholder="Summary"/>
</div>
我的validateFoo指令:
app.directive('validateFoo', function(){
return{
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var id= attr.id;
//if the checkbox is checked, see if the text field has been filled in
if(viewValue) {
var val= document.getElementById('summary-' + id).value;
if(val.length == 0) {
ctrl.$setValidity("summary", false);
return undefined;
}
else {
ctrl.$setValidity(id, true);
return viewValue;
}
}
});
}
}
});
我无法使验证适用于任何复选框,我不清楚使用什么用于&#34; ng-show&#34;在错误消息span元素中。
答案 0 :(得分:0)
首先,因为所有字段都将在名称为{{drug.drugName}}
的formController中注册。
第二件事是范围内没有myForm.{{drug.drugName}}.$invalid
。你可能试过myForm[drug.drugName].$invalid
。但它无论如何都不会起作用 - 看看 1。
我认为仍然没有正确的方法可以在name
中动态设置ng-repeat
字段。相反,你需要创建一个tour own指令,它将重复的列表元素构建为String,然后将其附加到HTML并编译它。
修改强>
我开发了一个解决方案:
http://jsfiddle.net/ulfryk/gejfeLp7/
编辑2:
我开发了更简单的解决方案(http://jsfiddle.net/ulfryk/5wq7539r/):
app.directive('fixRepeatedModelName', function () {
return {
link: function (scope, element, attrs, ngModelCtrl) {
if (!attrs.name) return;
ngModelCtrl.$name = attrs.name;
},
priority: '-100',
require: 'ngModel'
};
});
并将fix-repeated-model-name
属性添加到任何ng-model
,其中{{ }}
置于动态name
依赖)ng-repeat
内。它现在有效:)