AngularJS Convert Comma Separated String to Array Example

By Hardik Savani November 5, 2023 Category : Bootstrap jQuery Angular

When i was working on my Laravel angularjs application, i require to make array from comma separated string, I was not expert in angularjs so i was thingking how is it possible ?, But Finally i was found solution using custom angularjs Filter.

So, In this example, I will give you full example of how to convert comma separated string into array and how to print it. We will create array using split() of jquery. But if you know angularjs we can't do it anything directly from layout, So we should create our custom filter, as bellow you can see i created "customSplitString" filter.

Filter:

app.filter('customSplitString', function() {

return function(input) {

var arr = input.split(',');

return arr;

};

});

Ok, Now as bellow i give you full example of how to convert comma separated string to array, that way you can learn how is it work.

Example:

<!DOCTYPE html>

<html>

<head>

<title>Angularjs comma separated string to array</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>

<body>


<div ng-app="mainApp" ng-controller="myController" id="mainController" class="container">


<div ng-repeat="value in myArray">

<strong>Title:</strong> {{ value.title }}

<strong>List:</strong> {{ value.list }}

<br/>


<strong>List With filter:</strong>

<ul ng-repeat="elem in (value.list | customSplitString)">

<li>{{ elem }}</li>

</ul>


</div>


</div>


<script type="text/javascript">


var app = angular.module("mainApp", []);


app.controller('myController', function($scope, $timeout) {

$scope.myArray = [

{'title' : 'Language','list' : 'PHP,C,C++,Java,Jquery,SQL'},

{'title' : 'Color','list' : 'Red,Blue,Pink'},

{'title' : 'Company','list' : 'BMW,Swift'},

];

});


app.filter('customSplitString', function() {

return function(input) {

var arr = input.split(',');

return arr;

};

});


</script>


</body>

</html>

I hope it can help you...

Shares