Reputation: 3289
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:
Call the Javascript replace method when binding:
{{ myValue.replace("a", "A"); }}
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
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
};
})
Upvotes: 4