在以下应用程序中,如果客户已存在,我想显示错误消息。我试图通过循环客户名称来做到这一点,但它似乎不起作用。换句话说,如何使用角度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>
答案 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
:变量customers
和name
是什么?它们是未定义的。我认为它们应该是$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;
}