Split for ng repeat item?

2019-04-05 16:25发布

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.

3条回答
戒情不戒烟
2楼-- · 2019-04-05 17:03

commented delimiter here

angular.module('myFilters', []).
  filter('split', function() {
    return function(input, delimiter) {
      //var delimiter = delimiter || ',';

      return input.split(delimiter);
    } 
  });

You could use the filter like so: also added track by $index to avoid crash due to duplicate values

<div ng-repeat="item in somedata | split:',' track by $index">
查看更多
叼着烟拽天下
3楼-- · 2019-04-05 17:15

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

查看更多
放我归山
4楼-- · 2019-04-05 17:27

I guess I'm too late, but why not simply do this:

<div ng-repeat="item in somedata.split(',')">{{item}}</div>

works just fine.

JSBin for evidence!

查看更多
登录 后发表回答