将ng-model值设置为div文本

时间:2016-03-22 21:35:22

标签: javascript html angularjs

我想显示一个记录列表。数据是一个对象列表,每个对象都是这样的:

{
  date: "01/01/2001",
  time: "04:28 AM",
  message: "message strings here."
}

我希望按照按日期分组的方式显示它们。像这样:

08/01/2005
 04:28 AM message strings here.
 04:20 AM message strings here.
 02:12 AM message strings here.
07/05/2005
 03:32 PM message strings here.
 02:12 PM message strings here.

这是我的代码:

<div>{{date}}</div> <!--date is initialized in my angular controller to be the first date in the records.-->
<div ng-repeat="record in records">
    <div ng-if="record.date != date" ng-model="date">{{record.date}}</div> <!--here I expect date would be updated to record.date.-->
    <div>{{record.time}} {{record.message}}</div>
</div>

但我得到的结果如下:

08/01/2005
 04:28 AM message strings here.
 04:20 AM message strings here.
 02:12 AM message strings here.
07/05/2005
 03:32 PM message strings here.
07/05/2005 //This is displayed, means the date is not updated when it reach the first 07/05/2005 above.
 02:12 PM message strings here.

我在线搜索,很多模型数据绑定是用<input>绑定模型。但我不想要输入标签。 <div>中的ng-model似乎没有将模型更新为<div>中显示的文本。我想知道实现这个目标的正确方法。

2 个答案:

答案 0 :(得分:3)

我根据您的数据设置了一个示例:https://jsfiddle.net/63o96cf2/

原始答案:https://stackoverflow.com/a/14800865/3298029

查看:

<div ng-app ng-controller="Main">
  <ul ng-repeat="group in recordsToFilter() | filter:filterRecords">
    <b>{{group.date}}</b>
    <li ng-repeat="record in records | filter:{date: group.date}">{{record.time}}: {{record.message}}</li>
  </ul>
</div>

<强>控制器:

function Main($scope) {
  $scope.records = [{
    date: "01/01/2001",
    time: "03:28 AM",
    message: "message strings here."
  }, {
    date: "01/01/2001",
    time: "04:28 AM",
    message: "message strings here."
  }, {
    date: "01/01/2001",
    time: "06:28 AM",
    message: "message strings here."
  }, {
    date: "01/01/2002",
    time: "04:28 AM",
    message: "message strings here."
  }, {
    date: "01/01/2002",
    time: "05:28 AM",
    message: "message strings here."
  }];

  var indexedRecords = [];

  $scope.recordsToFilter = function() {
    indexedRecords = [];
    return $scope.records;
  }

  $scope.filterRecords = function(record) {
    var recordIsNew = indexedRecords.indexOf(record.date) == -1;
    if (recordIsNew) {
      indexedRecords.push(record.date);
    }
    return recordIsNew;
  }
}

答案 1 :(得分:1)

您需要在https://github.com/a8m/angular-filter#groupby

中使用“groupBy”过滤器

HTML

<ul ng-repeat="record in records | groupBy:'date'">
  {{ record.date }}
  <li ng-repeat="player in value">
   {{ record.time }} ... 
  </li>
</ul>