加入Angular模型数据

时间:2015-06-02 01:00:59

标签: javascript html angularjs

我正在使用ui-router状态并决定分离资源 - 列表"提交"以及"主题"的列表。在我的控制器中,我有两组数据:

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

1 个答案:

答案 0 :(得分:1)

要根据主题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>