另一天有另一个问题。我正在再次在我的Web应用程序上工作。现在我遇到了问题。主要浏览器 (http://www.w3schools.com/tags/att_select_required.asp) 不支持“必需”属性,它仅在第一个选项值为空时起作用。那么工作正常,如果表单是$无效的,并且它是由“请选择”留下的时候,则提交事件不会执行任何操作。
AngularJS指令为“html select required”
Land*:<br />
<select id="countries" name="country" data-ng-model="contact.country" required required-select>
<option value="">Please select</option>
<script type="text/javascript">
$(document).ready(function() {
var countries = {};
if (countries.length > 0) {
return countries;
} else {
$.get('WebKalkTool/country_de.xml', function(data) {
countries = data;
var that = $('#countries');
$('name', countries).each(function() {
$('<option />', {
text: $(this).text(),
}).appendTo(that);
});
}, 'xml');
}
});
</script>
</select>
<span class="error" data-ng-show="mandatory">Please select an item</span>
</p>
我正在寻找是检查是否为空值指令,然后显示 错误后提交,如果他们选择一个项目,该错误消失。
现在指令也许应该是这个样子:
authApp.directive('requiredSelect', function() {
return {
require: 'select',
link: function (scope, formElement, attr, formSelect) {
console.log('FORM : Linker called');
console.log(formSelect);
console.log(formSelect.selected.value); // is undefined..
scope.$watch(formSelect.selectedIndex.value, function() {
console.log("index changed"); // Always log when another index is selected
if (formSelect.selectedIndex.value == "") {
console.log("value="");
// only show error after submit OR has visited on span id mandatory (or add new template?
// Tell the form, it's invalid, select is invalid
} else if (formSelect.selectedIndex.value != "") {
console.log("index > 0");
// everything is fine, select is valid
} else {
console.log("FORMSELECT.SELECTINDEX = UNDEFINED");
// just 4 testing my link
}
});
}
};
});
因为兼容性想法和HTML5验证,我拿出了HTML5验证,无论如何只显示第一个提示。
它应该与输入字段的'required'属性相同,并且工作方式相同,我不想让我的提交按钮被禁用。也许我也可以删除这个“请选择”选项并将其留空。
或者,也许我只是不那么聪明足够做喜欢的事,等于:
<span class="error" data-ng-show="requestForm.place.hasVisited && requestForm.place.$invalid">Required!</span>
如果我们检查值或将selectedIndex,什么都无所谓。
感谢您的帮助,并认为
炭疽
问题是,我不想让它与ng-options一起使用,因为我也选择了具有2个硬编码值的选项。尽管我需要将我的国家用xml保存到一个变量中,但是这怎么回事^^ – Anthrax
无论ng-options里面的内容是什么,都将有益于Angular的双向数据绑定。这意味着您可以从一个空数组开始,然后用来自服务器的数据填充它。为了演示这个,我修改了这个plunker并添加了一个Add Country功能。这与您在接收数据时需要做的事情大致相同。希望这可以帮助。 –