0

I'm trying to avoid duplicates and not be allowed to add empty items. If I send the same titolo (example, Harry Potter) again, I don't want it to be added to the $scope.libri for the second time. How can I check it before adding? This is my code now:

angular .module('myApp', []) .controller('myCtr', function ($scope){

$scope.libri = [{id:'1',titolo:'Harry Potter',genere:'Fantasy',anno:'2001',autore:'J.K.Rowling'},
                {id:'2',titolo:'Il nome della rosa',genere:'Giallo',anno:'1994',autore:'Umberto Eco'},
                {id:'3',titolo:'Cado dalle nubi',genere:'Commedia',anno:'2014',autore:'Checco Zalone'}];
              
                


$scope.add = function () {
    
        $scope.libri.push({
            id: $scope.id,
            titolo: $scope.titolo,
            genere: $scope.genere,
            anno: $scope.anno,
            autore: $scope.autore
        });

        $scope.id = ' ';
        $scope.titolo = ' ';
        $scope.genere = ' ';
        $scope.anno = ' ';
        $scope.autore = ' ';
      };

1 Answer 1

1

Just use $scope.libri.find(x => x.titolo === $scope.titolo) in your add function before pushing to the array.

.find() from MDN

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. I tried with this code but it doesn't work it
This is the JS-standard way of finding an item in an array that matches a given criteria. If it's not working, then you're not doing it right.
Thank you Jacob. I'll try again it
Now it's ok the code! there was a problem with a ";" thank you Jacob
@lello77 Glad to hear :)

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.