1

I am using AngularJS as part of the MEAN stack. I have a model represented by job. job.tag is an attribute of the model represented by an array. The code below is the input field on a page used to edit the job attributes (the job has already been created with an array of various strings represented by job.tag).

<input data-ng-model="job.tag" type="text" id="tag" maxlength="50">

When the page used to edit the attributes is loaded - the input field is populated by a string representing the array which looks like "x,y,z" - when the array is converted into a string (the value which populates the text input field), commas are used to separate each element in the array. When the field is populated, how do I replace the commas with a whitespace, so the field displays "x y z"?

1
  • you could use a custom filter: ng-model="job.tab | take-out-comma-filter. Commented Feb 3, 2014 at 22:58

2 Answers 2

4

What you need to realize is that your model is an array and your input is expecting a string.
By default, javascript converts an array into a string (via array#toString) with array#join dash separated.

More than that, If your try to change the view it will override your array model with the string from the input. This is how ngModel two-way-data-binding works.

Fortunately , ngModel is so awesome that it allows you to intercept the two-way-binding with your own formatters and parsers. The $viewValue and the $modelValue` can have different values, and the binding is fully configurable.

use ngModelController:

  • $formatters to format / convert model -> view
  • $parsers to format / convert view -> model

Here is a plunker: http://plnkr.co/edit/HFjDHCHnBOStmYjk84ub?p=preview

A simple directive:

app.directive('array', function(){
  return {
    require: 'ngModel',
    link: function(scope,elm,attrs,ngModel){

      ngModel.$parsers.push(function(str){
        return str.split(/\s+/)
      })

      ngModel.$formatters.push(function(arr){
        return arr.join(' ');
      });
    }
  }
})

And the markup:

<input data-ng-model="job.tag" 
       type="text" 
       id="tag"
       data-array
       maxlength="50">
Sign up to request clarification or add additional context in comments.

Comments

0

Have you checked the javascript string object utility functions such as replace()?

http://www.w3schools.com/jsref/jsref_replace.asp

1 Comment

yes...I know how replace works - and that is what I am using to substitute, I just don't know how to implement it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.