gpt4 book ai didi

javascript - 使用 ng-repeat 时以 Angular 重复

转载 作者:行者123 更新时间:2023-11-30 08:43:22 26 4
gpt4 key购买 nike

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

我的第一个 ng-repeat 有效,但我使用 json 字符串的第二个无效。它提示 ng-repeat dupes 但我不明白为什么。我做错了什么?

请看这里的代码 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>

最佳答案

您不能直接使用 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"}]');
}

关于javascript - 使用 ng-repeat 时以 Angular 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24186527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com