我是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>
答案 0 :(得分:3)
您无法直接使用JSON,您必须将JSON反序列化为JS对象,如此JSFIDDLE所示。
<强> 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);