Search code examples
angularjsfilterdom-manipulation

Change model data on the fly in angularjs


I need to show a JSON array inside a textarea, but with some minor modification.

The JSON array located inside 'list' and $scope.list is bound to a JSON object.

How can I change delimiters on the fly from commas to \n in agnularjs?

http://jsfiddle.net/Pn5Xv/

List json:

{
    "items" : [ { "outputs" : ["one","two"] } ]
}

html:

<div ng-repeat="record in list">
  <textarea ng-model="record.outputs"></textarea>
</div>

Solution

  • You could create a custom filter for this task:

    JavaScript:

    myApp.filter('arrayToString', function() {
        return function(inputArray) {
            return inputArray.join("\n");
        };
    });
    

    And in your HTML:

    <div ng-repeat="record in list">
        <textarea>{{record.outputs | arrayToString}}</textarea>
    </div>
    

    Notes:

    • This you do not use ng-model anymore you need track changes by yourself and reverse the whole input, ng-change or ng-form should be helpful.
    • Make sure you filter is a dependency of you app.