The correct way to do things like this is to make a directive, this is pretty easy to do.
I'm sure you are used to jquery where you would do something like:
<table id="myTable">
<tr><td class="formatted">one text</td></tr>
<tr><td class="formatted">two text</td></tr>
<tr><td class="formatted">three text</td></tr>
</table>
And then do:
$('.formatted').each(function(){ ... format text here ...})
The directive is a very similar concept in angular. This would be the equivalent of the above:
<table id="myTable">
<tr><td formatted-text>one text</td></tr>
<tr><td formatted-text>two text</td></tr>
<tr><td formatted-text>class="formatted">three text</td></tr>
</table>
And then you define a directive:
myApp.directive("formattedText", function(){
return {
link: function(scope, element, attrs){
var text = element.text();
...do some formatting on text....
element.text(text);
}
}
});
In this case the link function will be called for every time angular encounters an element with a formatted-text
attribute.
You can even match on other things such as class or element name, by adding a restrict:
to your directive. Here is an example of the a few restrict value's and the equivalent jquery selector:
restrict: 'A' => $('[formatted-text]').each(link)
restrict: 'C' => $('.formatted-text').each(link)
restrict: 'E' => $('formatted-text').each(link)
So for example if I wanted to exactly match my initial jquery example above, you would do:
myApp.directive("formattedText", function(){
return {
restrict: 'C',
link: function(scope, element, attrs){
var text = element.text();
...do some formatting on text....
element.text(text);
}
}
});
Hopefully this makes sense and helps de-mistify directives a bit.