0
votes

I'm using the answer from Bindings Computed Property in Ember TextField, but would like to have it expanded upon a bit.

Here's my template:

{{input id="dollars" name="dollars" value=formattedDollars class="form-control"}}

And in my controller:

formattedDollars: function(key, value) {
    var model = this.get('model');
    if(value) {
        //This is the setter--make sure the stored value is an integer
        model.set('dollars', +value.toString().replace(/[^\d]/, ""));
    } else {
        //This is the getter--return a formatted value
        return model.get('dollars').toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
}.property('model.dollars')

This works if I am setting formattedDollars outside of the text field (e.g. model.incrementProperty('dollars', 10)), but if I actually type within the text input, the value does not stay formatted.

I've tried also returning value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") in the setter, but this didn't work either. How can I make it so that typing within the dollars input field automatically formats the number?

1

1 Answers

1
votes

You have to return the value in both cases - when getting or setting the computed property. So your code should be:

formattedDollars: function(key, value) {
    var model = this.get('model');
    if(arguments.length > 1) {
        //This is the setter--make sure the stored value is an integer
        model.set('dollars', +value.toString().replace(/[^\d]/, ""));
    } 
    //This is the getter--return a formatted value
    return model.get('dollars').toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    
}.property('model.dollars')