0

I have a problem with the validation about existing values. I don't know how to compare two values and add the new value only, when it isn't exist in the Database. I've tried with angular.forEach() but it adds the new object always when the compare (what I'm doing with angular.equals()) isn't false and thats wrong. The object have to be only one time in the database.

Here is my create function:

$scope.createItem = function (createItem) {
   //here I have to define a query to compare createItem.lname with the table list (array items from the db) in the view.

   //That was the code:
   angular.forEach(nameslist, function (value) {
     if (angular.equals(createItem.lname, value.lname)) {
           CrudService.create(createItem).then(
              function () {
                //success code
                $scope.createItem = null;
              },
              function (err) {
               //error code
              });
           }
     }
   });
} 

Can anyone give me some help.. I don't know how to solve it.

7
  • Where is your comparison code? Commented Jul 9, 2015 at 14:51
  • @tymeJV I've added my post Commented Jul 9, 2015 at 15:14
  • Is lname just a string? Commented Jul 9, 2015 at 15:17
  • @tymeJV is a property of the object. It is a string yes. nameslist is the array with the objects from the database Commented Jul 9, 2015 at 15:18
  • 1
    So why not just if (createItem.lname === value.lname) { - angular.equals is for object comparison Commented Jul 9, 2015 at 15:19

1 Answer 1

0
var itemAbsent = namelist.map(function(value){
   return value.name;
}).indexOf(createItem.name) < 0;

if (nameAbsent){
   CrudService.create(createItem).then(
          function () {
            //success code
            $scope.createItem = null;
          },
          function (err) {
           //error code
          });
       }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.