AngularJS重复行错误

时间:2016-07-27 17:04:14

标签: javascript angularjs json

当我想添加相同的信息时,它会给我一个错误的重复行。

这个问题来自$ scope.showSal和ng-repeat =“showSal中的行”。

如果我在$ index中使用ng-repeat =“showSal track中的行”我无法添加重复的行,我需要它。

如何解析和添加重复项?我试图制作JSON数据,但即使我使用stringify和parse方法也会出错...也许我没有很好地解析...

PS:我需要解析一个对象数组。

HTML文件:

<!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文件:

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);
    }
}]);

2 个答案:

答案 0 :(得分:1)

  

错误:ngRepeat:dupes Repeater中的重复键

添加track by $index

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

Doc

答案 1 :(得分:0)

替换,

class App extends Component {
    ...
    componentWillMount() {
        this.props.dispatch({type: 'BLAH'});
    }

    render(){
        return (<div>Data: {this.props.data}</div>);
    }
}

export default connect( state =>({
    data:state.data
}))(App);

要,

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

Here's the working FIDDLE