1

I have an input field that is supposed to contain numbers. It is bound to an object property. I want input entered as 4,5 to automatically get converted to 4.5 in both model and view.

HTML:

<input data-ng-model="productContent(product.Id).Org" value="{{productContent(product.Id).Org | replaceComma}}" />

Control:

$scope.productContent = function (prodId) {
    var content = $.grep($scope.productsContent, function (el) { return el.ProdId === prodId });
    return content[0];}  

Filter:

app.filter('replaceComma', function () {
            return function (val) {
                return (typeof val) == "string" ? val.toString().trim().replace(",", ".") : val
            };
        }); 

Result:

When I enter a number, at first the model (productContent) retrieves the correct object. Then the filter code is called and returns a correctly converted string. I would expect both the model and view to be updated to the filtered value, but both are updated with the unfiltered value. What am I doing wrong?

1 Answer 1

0

I have faced the same problem in the past but instead of creating my own filter, I took a different path and found something ready to use instead.

angular-input-masks by assisrafael one of my favourite angular extensions for this purpose:

https://github.com/assisrafael/angular-input-masks

Examples:

http://assisrafael.github.io/angular-input-masks/

Since the author has written the documentation, I don't want to get extensive on it and be outdated in the future. As a quick reference, look for ui-number-mask.

Maybe this is not a direct answer to your question, since it's not replacing commas with periods, but making you type the decimals instead.

On a side note, you can suppress the thousands separators with ui-hide-group-sep

I hope that's helpful, otherwise leave a comment and I'll be happy to continue to assist you!

-Helvio

Sign up to request clarification or add additional context in comments.

Comments

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.