我遇到了需要获取以下 JSON 响应的情况:
[
{
"url":"http://myurl1",
"tags":"tag 1.1,tag1.2,tag1.3"
},
{
"url":"http://myurl2",
"tags":"tag 2.1,tag2.2"
}
]
最终结果是:
<a href="http://myurl1">tag 1.1</a>
<a href="http://myurl1">tag 1.2</a>
<a href="http://myurl1">tag 1.3</a>
<a href="http://myurl2">tag 2.1</a>
<a href="http://myurl2">tag 2.2</a>
我在 jQuery 中构建了这个,只需在每个循环期间存储 url,将标签拆分到一个数组中,然后循环输出到 <a>
标签,同时拉入先前存储的单个 URL 实例。我真的很努力地尝试切换到 Angular ,这基本上就是我所拥有的。我有一种感觉,我把这个问题过于复杂化了,不管你信不信,我已经搜索了很长时间,并且已经研究了几个小时。
如果 json 数据是平坦的,我就完成了,但由于它不是平坦的,所以我陷入了困境。
我已经得到了这个,这很好,但它将所有标签转储到一个 <a>
中元素,不是我需要的。我假设我不会在 Controller 上创建嵌套循环:
标记:
<body ng-app="MyApp">
<div ng-controller="TagCtrl">
<a ng-repeat="tag in tags" href="{{tag.url}}">{{tag.tags}}</a>
</div>
</body>
Controller :
app.controller("TagCtrl", function($scope, $http) {
$http.get('data/tags.json').
success(function(data, status, headers, config) {
$scope.tags = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
我只是不知道在哪里将标签数据拆分到数组中并循环遍历它,即使我这样做了,如何将其返回到 View ?我的直觉告诉我,这应该在指令中,但我现在试图使其尽可能简单。
最后一件事,我没有能力更改 JSON 结构。
最佳答案
你可以这样做:
success(function(data, status, headers, config) {
$scope.tags = [];
data.forEach(function(urlObject) {
// Get array of tags from the string of tags
var tagsList = urlObject.tags.split(',');
tagsList.forEach(function(tag) {
$scope.tags.push({
url: urlObject.url,
tag: tag
});
});
});
})
然后使用您拥有的相同 HTML。
关于javascript - 在更新我的 Angular View 之前,如何操作从 JSON 响应派生的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34323241/