gpt4 book ai didi

javascript - 使用具有动态字段名称的 ng-messages

转载 作者:行者123 更新时间:2023-11-28 06:10:00 26 4
gpt4 key购买 nike

我有一个使用 ng-repeat 显示的字段列表。输入字段的名称是动态的。使用动态名称时如何让 ng-messages 工作?以下是我尝试过的方法,但这不起作用:

<form id="userForm" name="userForm" ng-submit="userForm.$valid && submit()" novalidate>
<div ng-repeat="uniqueField in uniqueFields">
<div>
<label>{{uniqueField.form_field_label}}</label>
<input required="{{uniqueField.isMandatory}}" name="text_{{uniqueField.form_field_id}}" ng-model="uniqueField.form_field_value" type="text">
<div ng-messages="userForm.{{uniqueField.form_field_id}}.$error" ng-if="userForm.$submitted && uniqueField.isMandatory == true">
<div ng-message="required">Please enter a {{uniqueField.form_field_label}}.</div>
</div>

</div>
</div>
</form>

最佳答案

您在输入字段的名称中添加了 text_ 前缀,但您查找了 userForm.{{uniqueField.form_field_id}}.$error。删除前缀,它应该可以工作:)

这是解决方案 HTML:

<div ng-app="demoApp" ng-controller="MainCtrl as ctrl">
<form id="userForm" name="userForm" ng-submit="userForm.$valid && ctrl.submit()" novalidate>
<div ng-repeat="uniqueField in ctrl.uniqueFields">
<div>
<label>{{uniqueField.form_field_label}}</label>
<input required="{{uniqueField.isMandatory}}" name="{{uniqueField.form_field_id}}" ng-model="uniqueField.form_field_value" type="text">
<div ng-messages="userForm[uniqueField.form_field_id].$error">
<div ng-message="required">Please enter a {{uniqueField.form_field_label}}.</div>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
</div>

和 Controller :

angular.module('demoApp', [])
.controller('MainCtrl', MainCtrl);

function MainCtrl($log) {
var ctrl = this;

function activate() {
ctrl.uniqueFields = [{
form_field_label: 'Name',
form_field_id: 'name',
form_field_value: '',
isMandatory: true
}]
}

activate();

ctrl.submit = function() {
$log.debug('form submitted');
}
}

工作 fiddle :https://jsfiddle.net/trollr/133hhwzx/

关于javascript - 使用具有动态字段名称的 ng-messages,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36492889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com