gpt4 book ai didi

javascript - 连接 Angular 模型数据

转载 作者:行者123 更新时间:2023-12-03 10:01:18 25 4
gpt4 key购买 nike

我正在使用 ui-router 状态并解析分离资源 - 一个“提交”列表和一个“主题”列表。在我的 Controller 中,我有两组数据:

...
app.controller('SubmitController', function ($scope, submissions, topics{
$scope.submissions = submissions;
$scope.topics = topics;
...

然后在html中,类似(最后几行注释代码解释了我需要什么):

...
<tr ng-repeat="sub in submissions">
<td ng-bind="sub.id"></td>
<td ng-bind="sub.title"></td>
<td ng-bind="sub.topic_id"></td>
<td ng-bind="sub.status"></td>
<!--
here I need a <td> with the "name" from the topic collection
where the current submission id = the matching topic id from
the topic collection
-->
...

我尝试过过滤器但无法使其工作。处理此类问题的最佳方法是什么?

TIA

最佳答案

要根据主题 id 获取主题名称,您必须在主题数组中找到主题,然后将名称分配给每个提交对象。

angular.forEach($scope.submissions, function(submission) {
var topic = $scope.topics.filter(function(tp) {
return tp.id = submission.topic_id;
})[0]; //Find the topic base on topic_id
submission.topicName = topic.name;
});

下面的工作片段,单击“运行代码片段”即可查看:

var app = angular.module('app', []);

app.controller('myCtrl', function($scope) {
$scope.submissions = [{
id: 1,
title: 'title 1',
topic_id: 1
}, {
id: 2,
title: 'title 2',
topic_id: 2
}, {
id: 3,
title: 'title 3',
topic_id: 2
}];

$scope.topics = [{
id: 1,
name: 'topic 1'
}, {
id: 2,
name: 'topic 2'
}];

angular.forEach($scope.submissions, function(submission) {
var topic = $scope.topics.filter(function(tp) {
return tp.id == submission.topic_id;
})[0];
submission.topicName = topic.name;
});

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app">
<div ng-controller="myCtrl">
<table>
<tr>
<th>ID</th>
<th>Title</th>
<th>Topic Id</th>
<th>Status</th>
<th>Topic name</th>
</tr>
<tr ng-repeat="sub in submissions">
<td ng-bind="sub.id"></td>
<td ng-bind="sub.title"></td>
<td ng-bind="sub.topic_id"></td>
<td ng-bind="sub.status"></td>
<td ng-bind="sub.topicName"></td>
</tr>
</table>
</div>
</div>

关于javascript - 连接 Angular 模型数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30585698/

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