gpt4 book ai didi

javascript - 如何在一个 AngularJS 指令中转换 jQuery 函数?

转载 作者:行者123 更新时间:2023-11-27 23:38:24 24 4
gpt4 key购买 nike

我必须使用指令验证表单,以便 AngularJS 能够启用或禁用提交表单按钮。

我在 jQuery 中有一个函数,但我需要 AngularJS 监视此行为。

此函数比较输入以防止每个输入中存在重复信息。

<form id="myform">
<table>
<tr>
<td><input name="currency1" class="required" unique="currency"/></td>
</tr>
<tr>
<td><input name="currency2" class="required" unique="currency"/></td>
</tr>
<tr>
<td><input name="currency3" class="required" unique="currency"/></td>
</tr>
<tr>
<td><input name="currency4" class="required" unique="currency"/></td>
</tr>
</table>

这就是函数

jQuery.validator.addMethod("unique", function(value, element, params) {
var prefix = params;
var selector = jQuery.validator.format("[name!='{0}'][name^='{1}'][unique='{1}']", element.name, prefix);
var matches = new Array();
$(selector).each(function(index, item) {
if (value == $(item).val()) {
matches.push(item);
}
});

return matches.length == 0;
},
"Valor Repetido"
);


jQuery.validator.classRuleSettings.unique = {
unique: true
};

$("#myform").validate();

$("#validate").onBlur(function() {
$("#myform").valid();
});

和CSS

label.error { color: red }

有人可以帮助我吗?

最佳答案

您可以使用一个对象数组来保存所有值,并深入观察它。
在 Controller 中:

$scope.currencies =
[{'value':'val1'},{'value':'val2'},{'value':'val1'} ];

$scope.$watch('currencies', function(){
$scope.duplicates = false;
var found = [];
$scope.currencies.forEach(function(currency){
if(!(found.indexOf(currency.value)+1))
found.push(currency.value);
else $scope.duplicates = true;
});
},true); //The 'true' last parameter is the signal to deep watch.

表中的每个输入都与 ng-model 绑定(bind)到 $scope.currencies 中的对象这样深度观察就能立即看到任何变化。您可以使用 ng-repeat 生成输入列表指令:

<tr ng-repeat="currency in currencies">
<td><input type="text" ng-model="currency.value"></input></td>
</tr>

然后对于提交按钮,有 <input type="submit" ng-disabled="duplicates"></input>

如果您愿意,您可以添加按钮来添加或删除 $scope.currencies 中的元素,它会立即反射(reflect)在 View 中。

Plunker sample

关于javascript - 如何在一个 AngularJS 指令中转换 jQuery 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33924539/

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