javascript Angular 将 ng-messages 动态设置为 name 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31456539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular dynamically set ng-messages to name attribute
提问by CSharpBeginner
I dynamically create inputs and want also validate every one of them but cant set correctly the ng-messages attribute to the field name property which is dynamically generated.
我动态创建输入并希望验证其中的每一个,但无法将 ng-messages 属性正确设置为动态生成的字段名称属性。
<input ng-model="sub.name" name="subName{{$index}}" class="form-control" placeholder="name" required maxlength="20" />
<div class="field-error" ng-messages="form.subName{{$index}}.$error" ng-show="form.Name.$touched" role="alert">
<div ng-message="required">Name is required.</div>
</div>
I got problem with second line where i set the ng-messages dynamically to ng-messages. How can I do this?
我在第二行遇到问题,我将 ng-messages 动态设置为 ng-messages。我怎样才能做到这一点?
回答by Helori
Accessing the properties of your form object can also be done using brackets, which should solve your problem :
也可以使用方括号访问表单对象的属性,这应该可以解决您的问题:
<input ng-model="sub.name" name="subName{{$index}}" class="form-control" placeholder="name" required maxlength="20" />
<div class="field-error" ng-messages="form['subName' + $index].$error" ng-show="form.Name.$touched" role="alert">
<div ng-message="required">Name is required.</div>
</div>