如果我不理解某些内容需要澄清,请耐心等待,因为我还是Angular的新手,如果可以的话,请简化Angular新手的解释,谢谢!
我正在处理从数据库中提取的数据的表格显示,并使用ng-repeat将其生成为“results.items中的项目”。项目有三种“类型”,我们只称它们为“标题”,“动作”和“评论”。由于results.items是数组,因此无论类型如何,$index
都按项目放置在整个数组中。
我想要做的是只能编号一种类型的项目item.type=='action'
。显然,如果我只是把
<td ng-show="item.type=='action'">{{$index}}</td>
它将通过原始数组索引,所以不是让我的数据按顺序编号为1,2,3等的每个'动作',我最终将它们编号为数组,如下所示: 5,8,9,12,15,16,22。
任何人都可以通过直接的方式在我的控制器中设置新$index
(例如'$actionIndex'
)的生成,这将只重新索引类型为=的项目= '动作'?理想情况下,我希望能够在我的控制器中为此指定$scope
函数,然后使用ng-model或其他东西调用它。
我知道代码抽样部门缺少这个问题 - 在这种情况下对我来说有点尴尬因为我还是Angular的新手,我不能仅仅根据公司NDA规则复制实际代码。感谢您对我的支持以及您可以提供的任何帮助。
修改/更新:
在回顾了pixelbits提供的解决方案之后,我想知道我应该在这里做些什么,而不是为"type==action"
的每个项目创建一个新的关联id#,只需将每个连续项目增加"type==action"
?< / p>
我不想完全从显示中过滤"type!=action"
的项目。现在它正在使用包含ng-repeat
和排序,以便其他类型的“项目”(如果适用)在此类型(item==action
)下以正确的顺序出现以解释/增强它。这意味着我<tr>
将每行ng-repeat="item in items"
个单元格中的<span>
和td
标记设置为ng-show
,具体取决于type
。我没有看到如何在逻辑上使用基于ng-repeat
的其他type
。我只想重新索引所有type==action
项并显示新的索引数字,而不是更大的默认数组“items
”本身。
仍在努力......
以下是模板中的代码段,用于说明:
<tbody>
<tr ng-repeat="item in items" ng-class="{title: item.type=='title', action: item.type=='action', comment: item.type=='comment'}">
<td class="grid-2">
<span ng-show="item.type=='action'">{{$index}}</span>
<span ng-show="item.type!='action'"> </span>
</td>
<td class="action-text grid-8">
<span class="title regular-item" ng-show="item.type=='title'">
<h3>{{item.field}}</h3>
</span>
<span class="action regular-item" ng-show="item.type=='action'">{{item.field}}</span>
<span class="comment" ng-show="item.type=='comment'"><i>Comment by: {{item.author}}<br />{{item.field}}</i></span>
</td>
<td class="grid-2">
<span ng-show="item.type=='action'" class="timestamp" data-toggle="tooltip" data-original-title="{{item._created | date: 'hh:mm:ss a'}}">{{item._created | date: 'hh:mm:ss a'}}</span>
<span ng-show="item.type!='action'"> </span>
</td>
</tr>
</tbody>
因此,您可以看到我有一般的ng-repeat,然后模板根据类型将其排出。 “动作”是一种非常“重要”的类型,因为它具有其他人没有的特殊显示。
答案 0 :(得分:0)
您可以实现$ watch处理程序:
<强> JS 强>
app.controller('ctrl', function($scope, $filter) {
$scope.result = ...;
$scope.actionList = [];
$scope.$watchCollection('result.items', function(newArr) {
$scope.actionList = $filter('filter')(newArr, { type: 'action' }, true);
});
});
<强> HTML 强>
<ul>
<li ng-repeat="item in actionList">{{ $index }}</li>
</ul>
答案 1 :(得分:0)
在尝试了这里建议的pixelbits失败后,我最终回到了服务并插入了一个我可以放在模板中的计数器。
相关摘要:
}, function(response) {
var items = response.data;
var i = 1;
_.each(items, function(item) {
if (item.type == 'action') {
item.counter = i++;
}
});
callback(response.data);
});
在模板中:
<span ng-show="item.type=='action'">{{item.counter}}.</span>
我的一个常见问题是“过度思考”一个问题(在我看来它比它需要的更复杂),这也不例外!希望这也有助于未来的其他人。