如何验证角度js

时间:2014-06-29 02:26:47

标签: javascript angularjs

在以下应用程序中,如果客户已存在,我想显示错误消息。我试图通过循环客户名称来做到这一点,但它似乎不起作用。换句话说,如何使用角度js检查客户名称是否已存在?

这是我到目前为止所做的:

<script>
  //create an object that ties with module
  // pass an array of dependencies
  var myApp = angular.module('myApp', []); 
  //create controller
  myApp.controller('MainController', function($scope){
    $scope.customers = []; 
    $scope.addCustomer = function(){
      $scope.date = new Date();
      $scope.customers.push({
        name: $scope.customer.name
      });

      for(var i = 0; i < $scope.customers.name.length; i++) {
        if(customers[i].name == name) {
          alert('Customer already exists'); 
        }
      }     
    };

    $scope.removeCustomer = function(index) {
      $scope.customers.splice(index,1);
    };
  });

</script>

2 个答案:

答案 0 :(得分:1)

我认为你在for陈述中犯了错误。

您的代码

for(var i = 0; i < $scope.customers.name.length; i++) { ...

应该是:

for(var i = 0; i < $scope.customers.length; i++) { ...

编辑1
我已根据您现有的代码添加完整版验证:

$scope.addCustomer = function() {    
  var isExisted = false;  

  for(var i = 0; i < $scope.customers.length; i++) {
    if($scope.customers[i].name == $scope.customer.name) {
      isExisted = true;
      break;
    }
  }

  if (isExisted) {
    // inform user
    alert('Customer already exists');
  } else {
    // save new customer
    $scope.customers.push({
      name: $scope.customer.name
    });

    // clear the input, maybe
    $scope.customer = {};
  }
};

编辑2

我已添加了对您的代码的评论:

  • 在循环中,条件逻辑$scope.customers.name.length是错误的。更正为$scope.customers.length。你想循环数组$scope.customers,对吧?
  • 检查现有的条件逻辑也是错误的。 customers[i].name == name:变量customersname是什么?它们是未定义的。我认为它们应该是$scope.customers$scope.customer.name
  • 找到现有客户后,您应添加break声明。不需要继续循环,对吗?
  • 您应该改进您的代码风格。请注意缩进和分号。

答案 1 :(得分:0)

创建一个单独的函数来检查并在add函数中调用它:

$scope.addCustomer = function(){
    $scope.date = new Date();

    if (doesCustomerExist($scope.customer.name) == false) {
        $scope.customers.push({
            name: $scope.customer.nam
        });  
    }
}

function doesCustomerExist(name) {
    for (var i = 0; i < $scope.customers.length; i++) {
        if ($scope.customers[i].name == name) return true;
    }
    return false;
}