[javascript] How to split a string with angularJS

I wanted to know if I can split a string simply in angularJS. I have my

 $scope.test = "test1,test2";

in my controller and in my view, I wanted to do something like that

{{test[0] | split(',')}}
{{test[1] | split(',')}}

I've seen a lot thing about input and ng-change calling a function in the controller that split the string or something with ng-list but nothing works in my case.

thx to all.

This question is related to javascript angularjs

The answer is


You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.


You can try something like this:

$scope.test = "test1,test2";
{{test.split(',')[0]}}

now you will get "test1" while you try {{test.split(',')[0]}}

and you will get "test2" while you try {{test.split(',')[1]}}

here is my plnkr:

http://plnkr.co/edit/jaXOrZX9UO9kmdRMImdN?p=preview


Thx guys, I finally found the solution, a really basic one.. In my controller I have

$scope.mySplit = function(string, nb) {
    var array = string.split(',');
    return array[nb];
}

and in my view

{{mySplit(string,0)}}