dupes in angular when using ng-repeat

会有一股神秘感。 提交于 2019-12-11 06:22:29

问题


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


来源:https://stackoverflow.com/questions/24186527/dupes-in-angular-when-using-ng-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!