Search code examples
javascripthtmlangularjsdomangularjs-filter

AngularJS: How can I get the DOM element from a filter


The problem is as follows: I have got several html sites where a filter ("myFilter") is applied.

    angular.module('myApp', [])
    .filter('myFilter', function() {
            return function(input) {
                //do something with the input
                return input;
            };
    })

The filter is applied within different tags with no special id's or classes, like so:

    <span>{{'some_string | myFilter'}}</span>

or

    <div>{{'some_other_sring' | myFilter}}</div>

I would now like to add classes or styles to the elements in which the filter is used (for some testing purposes). My question is, if there is a way to get the DOM elements in the filter function? At the moment I don't see a straight forward way of doing it and would be thankful for a specific or general idea of how to achieve it. Thanks in advance for any help.

P.S. I know I could use a directive instead of the filter but, the filter is already distributed in tons of html so I would prefer to work with the filter.


Solution

  • There is no way to do that using filter. Use directive instead. For example:

    angular.module('myApp', [])
    .directive('myDirective', function() {
        return {
            link: function(scope, element, attributes) {
                element.addClass('some-class');
                ...
            }
        };
    });
    

    Using regex find/replace it won't be too hard to add a directive to all elements that use the filter you wanted to accomplish this with.