拆分 ng 重复项? [英] Split for ng repeat item?
问题描述
简单的问题 - 如果我的控制器中有这个:
$scope.somedata = 'Item 1, Item 2';//从别的东西设置
有没有办法在 ngRepeat 表达式中为我的视图拆分一些数据?类似的东西:
<div ng-repeat="item in somedata | split(',')">{{item}}</div>
哪个不起作用...
或者我必须这样做
$scope.somedata = 'Item 1, Item 2';//从别的东西设置$scope.items = somedata.split(',');
然后
解决方案 |
右边的字符串被解析为过滤器的名称(通常它们是字符串格式化过滤器,但 angular团队还提供了 filter
过滤器,它返回一个过滤后的数组(有点误导,因为两者共享相同的名称).您可以创建自己的拆分过滤器来完成您想要的:
angular.module('myFilters', []).过滤器('拆分',功能(){返回函数(输入,分隔符){var 分隔符 = 分隔符 ||',';返回 input.split(delimiter);}});
您可以像这样使用过滤器:
或者指定一个分隔符:
考虑上面的伪代码,因为我还没有测试过.
Le plunker:http://plnkr.co/edit/hk6F0Y6p5YAXv6fyXfSz?p=preview一个>
Simple question- if I have this in my controller:
$scope.somedata = 'Item 1, Item 2'; // set from something else
is there a way to split somedata for my view in a ngRepeat expression? Something like:
<div ng-repeat="item in somedata | split(',')">{{item}}</div>
which doesnt work...
Or do I have to do
$scope.somedata = 'Item 1, Item 2'; // set from something else
$scope.items = somedata.split(',');
and then
<div ng-repeat="item in items>{{item}}</div>
I think I'm not really understanding what I can do in an expression in AngularJS.
解决方案 The string the right of the |
is resolved to the name of a filter (usually they are string formatting filters, but the angular team has also provided the filter
filter, which returns a filtered array (a bit misleading because the two share the same name). You could create your own split filter to accomplish what you want:
angular.module('myFilters', []).
filter('split', function() {
return function(input, delimiter) {
var delimiter = delimiter || ',';
return input.split(delimiter);
}
});
You could use the filter like so:
<div ng-repeat="item in somedata | split">
Or specify a delimiter:
<div ng-repeat="item in somedata | split:,">
Consider the above pseudo-code because I haven't tested it.
Le plunker: http://plnkr.co/edit/hk6F0Y6p5YAXv6fyXfSz?p=preview
这篇关于拆分 ng 重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文