使用ng-repeat时有角度的欺骗

时间:2014-06-12 14:07:24

标签: javascript angularjs angularjs-ng-repeat ng-repeat

我是Angular的新手,ng-repeat对我不起作用。

我的第一个ng-repeat工作但第二个我使用json字符串不是。它抱怨ng-repeat欺骗,但我不明白为什么。我做错了什么?

请在此处查看代码 JSFiddle

或在这里:

<!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>

3 个答案:

答案 0 :(得分:3)

您无法直接使用JSON,您必须将JSON反序列化为JS对象,如此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"}]');
}

答案 1 :(得分:1)

解析它 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"}]');

答案 2 :(得分:1)

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