dupes in angular when using ng-repeat

2019-08-15 05:05发布

问题:

I'm new to Angular and ng-repeat isnt working for me.

My first ng-repeat works but the second one where im using a json string isn't. Its complaining about ng-repeat dupes but I dont understand why. What I'm I doing wrong?

see the code here JSFiddle

or here:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>test</title>
</head>
<body>

    <div ng-app ng-controller="AController">

        <ul>
            <li ng-repeat="item in firstTest">
                {{item}}
            </li>
        </ul>

        <hr />

        <ul>
            <li ng-repeat="item in secondTest">
                {{item}}
            </li>
        </ul>

    </div>

    <script src="angular.min.js"></script>

    <script type="text/javascript">
        function AController($scope) {
            $scope.firstTest = {
                a: "123",
                b: "234"
            };

            $scope.secondTest = '[{"Price": 123,"ProductName": "apple"},{"Price": 234,"ProductName": "pear"}]';
        }
    </script>

</body>
</html>

回答1:

You can not use JSON directly you have to deserialize the JSON to JS Objects as shown in this JSFIDDLE.

JSON.Parse

HTML:

<div ng-app ng-controller="AController">
    <ul>
        <li ng-repeat="item in firstTest">
            {{item}}
        </li>
    </ul>
    <hr />
    <ul>
        <li ng-repeat="item in secondTest">
            {{item.Price}}
        </li>
    </ul>
</div>

JS:

function AController($scope) {
    $scope.firstTest = {
        a: "123",
        b: "234"
    };

    $scope.secondTest = JSON.parse('[{"Price": 123,"ProductName": "apple"},{"Price": 234,"ProductName": "pear"}]');
}


回答2:

Parse it http://jsfiddle.net/64dAE/

<ul>
    <li ng-repeat="item in secondTest">
        {{item.Price}}
    </li>
</ul>

js:

$scope.secondTest = JSON.parse('[{"Price": 123,"ProductName": "apple"},{"Price": 234,"ProductName": "pear"}]');


回答3:

$scope.secondTest= JSON.parse($scope.secondTest);