如何检查输入字段中输入的值是否已在angularjs中可用

时间:2017-01-07 19:27:43

标签: javascript html css angularjs

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

我有一个输入字段,按键时我想用names数组中的值检查输入字段值,如果values数组中已存在值,则显示错误消息,并禁用该按钮。如果输入的值不在names数组中,我不想显示错误消息并启用Add按钮。这是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);
  });
}]);

2 个答案:

答案 0 :(得分:0)

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

在上面添加了ID以从文本字段中检索值

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

  for (i = 0; i < $scope.names.length; i++) {
    if (document.getElementById('getValue').value === $scope.names[i]) {
         alert('something'); 
         return;
    };
  };

然后运行一个函数来检查数组中的名称以及是否有alert和stop函数。

要隐藏添加到<button on-keypress="submit()" class="random">Add</button>的类并从控制器$('.random').hide();调用,请注意它是在这里使用的JQuery。

答案 1 :(得分:0)

不是每次循环遍历数组,而是使用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>

<强>控制器

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

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