Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
KeizerBridge Avatar asked Jul 03 '13 12:07

KeizerBridge


People also ask

How to separate string in angular?

You need to use split() function.

How to split an string in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How to split character in JavaScript?

The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated.


1 Answers

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])     .filter('split', function() {         return function(input, splitChar, splitIndex) {             // do some bounds checking here to ensure it has that index             return input.split(splitChar)[splitIndex];         }     }); 

From here, you can use a filter as you originally intended

{{test | split:',':0}} {{test | split:',':0}} 

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

like image 56
leon.io Avatar answered Sep 17 '22 04:09

leon.io