user11081980
user11081980

Reputation: 3289

AngularJS - replacing a value in the view or controller

I need to bind a value coming from the model in a span element, but I need to replace some characters.

I figured I have two options:

  1. Call the Javascript replace method when binding:

    {{ myValue.replace("a", "A"); }}

  2. Have a myReplace function in the controller and call it when binding from the view:

    // Controller: vm.myReplace = function(string) { return string.replace("a", "A"); } // View: {{ vm.myReplace(value) }}

I am wondering if there are any other options, and what is the recommended way (or most common way) in AngularJS. Thank You.

Upvotes: 1

Views: 3101

Answers (1)

Omri Aharon
Omri Aharon

Reputation: 17064

I'd go for a filter for the use case you're describing. That way it also changes automatically as your text changes.

It goes like this:

HTML:

<div>{{name | replaceA}}</div>  

Filter:

filterExample.filter('replaceA', function () {
    return function (text) {
        if (!text) {
            return text;
        }

        return text.replace(/\a/g, 'A'); // Replaces all occurences
    };
})

Fiddle

Upvotes: 4

Related Questions