javascript - AngularJS Avoid duplicates when updating a CRUD table (normal add to table works) -
i trying create simple crud table not allow duplicate names. have been able duplicate work when adding contact table, not seem working when updating table.
below simple function verified uniqueness of contact:
// (allowed) dupcount 0 when adding, , 1 when in update // mode allow saving contact without making changed. var isunqiue = function(newcontact, dupcount) { var returnval = true; var count = 0; (var contact in $scope.model.contacts) { if (newcontact.name.touppercase() === $scope.model.contacts[contact].name.touppercase()) { count++; } } if (count > dupcount) { returnval = false; } return returnval; }
for reason, duplicate in update mode not working @ all! if update 3 or 4 contacts same name, 'if (count > dupcount) ... ' statement seem compare 1 , 1.
here jsfiddle entire code: https://jsfiddle.net/7ay9nslv/
simple scenario:
add 'adam, smith' 1. edit 'adam, smith', save without changing > 2. add 'adam, smith' again > duplicate error add 'adam, smithx' 3. edit 'adam, smithx' 'adam, smith' > duplicate error
also note, data in table sorted , all, not sure if passing $index controller useful (unless sorting doesn't change data index).
first you're doing redudant in for-loop
, can use array.prototype.foreach() method find if index exists:
// use named function stop looping correctly var indexexists = -1; $scope.model.contacts.foreach(function loop(contact, index) { if (loop.stop) { return; } if (contact.name.touppercase() === newcontact.name.touppercase()) { indexexists = index; loop.stop = true; } });
or es6:
var indexexists = $scope.model.contacts.findindex(function(contact) { return contact.name.touppercase() === newcontact.name.touppercase(); });
or using findindex method of underscorejs:
_.findindex($scope.model.contacts, function(contact) { return contact.name.touppercase() === newname });
then check:
return indexexists == -1 && indexexists !== idx || indexexists === idx && $scope.model.contacts[indexexists].name.touppercase() === newname;
it returns true if user doesn't exists or if exists , it's editing itself.
now, let's go error:
you've commited 2 mistakes:
- you're passing old contact
unique
function, should pass new contact.
change
this:
if (isunqiue(contact, 1)) {
for:
if (isunqiue($scope.model.selected, 1)) {
- you're attributting
$scope.error
old contact, should this:
$scope.errorcontact = $scope.model.selected;
Comments
Post a Comment