In Angular, how do I efficiently split input items into an array

20,111

ngList will do exactly what you want.

Text input that converts between comma-separated string into an array of strings.

Share:
20,111
George Ananda Eman
Author by

George Ananda Eman

Interior designer slash web designer, if that makes any sense

Updated on June 21, 2020

Comments

  • George Ananda Eman
    George Ananda Eman almost 4 years

    When binding input value to an ng-model like so:

    <input type="text" ng-model="array">
    

    how do I bind the input text as an array? So if I input one, two, three, the resulting model will be [ "one","two","three ].

    Right now this is how I'm achieving this:

    <input type="text" ng-model="string" ng-change="convertToArray()">
    

    And in my controller:

    $scope.convertToArray = function(){
        $scope.array = $scope.string.split(',');
    }
    

    It works fine but I don't think it's best practice because I'm making a $scope.string variable and then hardcoding the destination array.

    Is it possible to just have the input's model set into array and then have the input pass through the function before being bound to the scope?

  • Nikhil Nanjappa
    Nikhil Nanjappa almost 6 years
    The link is broken.
  • Mark Rajcok
    Mark Rajcok almost 6 years
    Link is fixed :)