How to split a string and use in `ng-repeat'

2020-07-24 04:49发布

From the back-end, I am getting a string as construction,apply - that means 2 words together.

Now I need to break them into 2 words and I need to use the ng-repeat. I created a filter to do that. It splits the string into an array with a length of 2, but how to use this in ng-repeat?

Here is my code :

    <div class="column design">
//app.Phase here is : `construction,apply`
                    <span ng-repeat="value in activeApp.Phase || commaBreak">{{$index}}</span> //instead of index i would like to show the word.
                </div>

my filter:

angular.module("tcpApp")
    .filter("commaBreak",

function () {

    return function (value) {
        if (!value.length) return;

        return value.split(',');
    }
});

What am I doing wrong here?

2条回答
欢心
2楼-- · 2020-07-24 05:26

I think this should work :

        <div class="column design">
            <span ng-repeat="value in activeApp.Phase.split(',') || commaBreak">{{$index}}</span> //instead of index i would like to show the word.
        </div>

http://jsfiddle.net/HB7LU/16458/

查看更多
forever°为你锁心
3楼-- · 2020-07-24 05:28

Here it is:

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', ['$scope', function($scope) {
    $scope.name = "construction,apply";
}]);

myApp.filter("commaBreak", 

    function () {

        return function ( value ) {

            if( !value.length ) return;

            return value.split(',');

        }

});

On html part you need to use the single OR.

<div ng-controller="MyCtrl">
    <p ng-repeat="value in name | commaBreak">{{value}}</p>
</div>

Here is the working example: http://jsfiddle.net/HB7LU/16459/

查看更多
登录 后发表回答