0

i have ng click event like this :

$scope.submitInfo = function myfunction() {
        var itemToAdd = {
            Id : generateUUID(),
            Name: $scope.Name,
            Email: $scope.Email,
            Phone: $scope.Phone
        };
        $scope.Info.push(itemToAdd);
    }

my problem is, i want to check if the same ID or Name is not already exist in $scope.Info collection.

i am purly foucs on angular.js, i am looking for best solution for this kind of scenario

vir
  • 55
  • 1
  • 6
  • you'll have to iterate through the collection and compare each row to the data being added. – Claies May 15 '15 at 10:34
  • 1
    possible duplicate of [Array .push() if does not exist?](http://stackoverflow.com/questions/1988349/array-push-if-does-not-exist) – Alex May 15 '15 at 10:35

3 Answers3

0

You could use $filter.

Something like this:

$scope.submitInfo = function myfunction() {
    var itemToAdd = {
        Id : generateUUID(),
        Name: $scope.Name,
        Email: $scope.Email,
        Phone: $scope.Phone
    };
    var foundElement = $filter('filter')($scope.Info, {Name: $scope.Name}, true);

    if (foundElement.length === 0) {
        $scope.Info.push(itemToAdd);
    }
};

Of course, you'll need to inject $filter in your controller/factory/whatever

rpadovani
  • 7,101
  • 2
  • 31
  • 50
0

Try this - Inside your submit function write below code i.e

$scope.submitInfo = function myfunction() {
    var itemToAdd = {
        Id : generateUUID(),
        Name: $scope.Name,
        Email: $scope.Email,
        Phone: $scope.Phone
    };
    if(($scope.Info.indexOf(itemToAdd.id) != -1) || ($scope.Info.indexOf(itemToAdd.Name) != -1) {
         $scope.Info.push(itemToAdd);
    }
}
User2
  • 1,293
  • 8
  • 17
0

You can use the native Javascript filter (not supported by IE8) to check if there is an element with that name:

var duplicates = $scope.Info.filter(function(item) {
    return item.Name = $scope.Name;
});
var nameExists = duplicates.length > 0;

And your complete method:

$scope.submitInfo = function myfunction() {
    var duplicates = $scope.Info.filter(function(item) {
        return item.Id = $scope.Name;
    });
    var nameExists = duplicates.length > 0;

    if (!nameExists) {
        var itemToAdd = {
            Id : generateUUID(),
            Name: $scope.Name,
            Email: $scope.Email,
            Phone: $scope.Phone
        };
        $scope.Info.push(itemToAdd);
    }
}
idrosid
  • 7,983
  • 5
  • 44
  • 41