gpt4 book ai didi

javascript - 如何检查在输入字段中输入的值在AngularJS中是否已经可用

转载 作者:行者123 更新时间:2023-11-28 05:09:07 25 4
gpt4 key购买 nike

我想知道在下面的示例中如何检查输入字段中输入的值是否已经可用。

我有一个输入字段,按下按键时我想用名称数组中的值检查输入字段值,如果名称数组中已存在该值,则显示错误消息,并禁用该按钮。如果输入的值不存在于名称数组中,我不想显示错误消息并启用“添加”按钮。这是 plunkr - https://plnkr.co/edit/rz0tjxhEajz7848Ws3ig?p=preview

html -

<!DOCTYPE html>
<html>

<head>
<script src="angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>

</head>

<body ng-app="test" ng-controller="testController">
Name: <input type="text"/>
<button on-keypress="submit()">Add</button>
</body>

</html>

脚本 -

var testController = angular.module('test', []);

testController.controller('testController', ['$scope', function($scope) {


$scope.names = ["name1","name2","name3"];

angular.forEach($scope.names, function(x) {

console.log(x);
});
}]);

最佳答案

不要每次都循环遍历数组,而是使用 ng-change 并使用 array.prototype.includes() 检查重复项。

Updated Plunkr

HTML:

  <body ng-app="test"  ng-controller="testController">
Name: <input type="text" ng-change="checkName()" ng-model="name"/>
<button ng-keypress="submit()">Add</button>
<p ng-show="showError">Name already exists</p>
</body>

Controller :

$scope.names = ["name1","name2","name3"];
$scope.showError = false;

$scope.checkName = function (){
if($scope.names.includes($scope.name)){
$scope.showError = true;
} else {
$scope.showError = false;
}
}

关于javascript - 如何检查在输入字段中输入的值在AngularJS中是否已经可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41525577/

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