Doro
Doro

Reputation: 355

AngularJS duplicate rows error

When I want to add the same information it warm me an error of duplicates row.

This problem it comes from $scope.showSal and ng-repeat="rows in showSal".

If I use ng-repeat="rows in showSal track by $index" I can not add duplicate rows and I need it.

How I can make to parse and add duplicates? I tried to make JSON data, but it take error even I use stringify and parse method... maybe I doesn't implemented too well the parsing...

PS: I need to parse an array of objects.

HTML file:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Research project</title>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <script src="js/app/research.js"></script>
    </head>
    <body ng-app="testApp" ng-controller="mainCtrl">
        <table>
            <thead>
                <tr>
                    <th>Nr.</th>
                    <th>An</th>
                    <th>Den</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="rows in showSal">
                    <td>{{rows.id}}</td>
                    <td>{{rows.an}}</td>
                    <td>{{rows.den}}</td>
                </tr>
            </tbody>
        </table>

        <form id="add-content" ng-controller="addInfoCtrl" ng-submit="addInfoDb()">
                <br/>
                <div class="controls">
                        <button type="submit" style="width: 220px;">Adauga salariu</button>
                </div>
        </form>
    </body>
</html>

JavaScript file:

var app = angular.module("testApp", []);

app.controller('mainCtrl', ['$scope', '$sce', '$document', function($scope, $sce, $document) {  
    $scope.showSal = [
        { id: '1', an: '2016', den: 'Oracle' },
        { id: '2', an: '2016', den: 'Oracle' }
    ];
}]);

app.controller('addInfoCtrl', ['$scope', function($scope) { 
    $scope.testAdd = { id: '100', an: '2016', den: 'Oracle' }

    $scope.addInfoDb = function() {
        $scope.showSal.push($scope.testAdd);
        console.log($scope.showSal.length);
    }
}]);

Upvotes: 0

Views: 238

Answers (2)

Yuva Raj
Yuva Raj

Reputation: 3881

Replace,

    $scope.showSal.push($scope.testAdd);

to,

    $scope.showSal.push(angular.copy($scope.testAdd));

Here's the working FIDDLE

Upvotes: 0

underscore
underscore

Reputation: 6887

Error: ngRepeat:dupes Duplicate Key in Repeater

Add track by $index

ng-repeat="rows in showSal track by $index"

Doc

Upvotes: 1

Related Questions