我正在使用Angular表单并尝试查看是否有更好的方法在表单中任何单元格的第一个初始焦点上触发事件。这样,事件只被调用一次。
我知道您可以通过向每个单元格元素添加属性ng-focus来触发事件。但是,这将导致每次表单的单元格元素获得焦点时触发事件。
让我们说这个表格有输入,文本区域和单选按钮等。
我希望这会有效,但事实并非如此:
在 ng-cell-has-focus="vm.clearAllMessages()"
元素上添加 <form>
属性
<form
name="vm.form"
novalidate
ng-cell-has-focus="vm.clearAllMessages()"
ng-submit="vm.form.$valid && vm.sendForm($event)">
<div class="form-group">
<label for="name-id">Name</label>
<input id="name-id"
name="name"
type="text"
ng-model="vm.formData.username"
autofocus
required>
<div class="error-message"
ng-messages="vm.form.name.$error"
ng-if="vm.form.name.$touched || vm.form.$submitted">
<div ng-message="required">Name is required.</div>
</div>
</div>
<div class="form-group">
<label for="email-id">Email</label>
<input id="email-id"
name="email"
type="email"
ng-model="vm.formData.emailAddress"
required>
<div class="error-message"
ng-messages="vm.form.email.$error"
ng-if="vm.form.email.$touched || vm.form.$submitted">
<span ng-message="required">Email address is required.</span>
<span ng-message="email">Please enter a valid email address.</span>
</div>
</div>
<div class="form-group">
<input id="radio-1-id"
name="radio"
type="radio"
value="First option"
ng-model="vm.formData.radio"
required>
<label for="radio-1-id">First option</label>
<input id="radio-2-id"
name="radio"
type="radio"
value="Second option"
ng-model="vm.formData.radio"
required>
<label for="radio-2-id">Second option</label>
<div class="error-message"
ng-messages="vm.form.radio.$error"
ng-if="vm.form.radio.$touched || vm.form.$submitted">
<span ng-message="required">Choose an option is required.</span>
</div>
</div>
<div class="form-group">
<label for="message-id">Message</label>
<textarea id="message-id"
name="message"
cols="1"
rows="4"
ng-model="vm.formData.message"
placeholder="Type in Message here ..."
required></textarea>
<div class="error-message"
ng-messages="vm.form.message.$error"
ng-if="vm.form.message.$touched || vm.form.$submitted">
<div ng-message="required">Message is required.</div>
</div>
</div>
<div class="form-group">
<label for="terms-id">Agree to Terms of Use</label>
<input id="terms-id"
name="terms"
type="checkbox"
ng-model="vm.formData.terms"
required>
<div class="error-message"
ng-messages="vm.form.emailConfirm.$error"
ng-if="vm.form.emailConfirm.$touched || vm.form.$submitted">
<div ng-message="required">You must agree to Terms of Use.</div>
</div>
</div>
<button type="submit">SUBMIT</button>
</form>