javascriptangularjsangular-materialcustom-directive

Extend Angular Material directive and add class to child node


I'm trying to work around a known bug in Angular Material for autocompletes, where adding any classes to the autocomplete aren't carried down to the md-input-container child elements. Tracked bug here. Following some of the basic instructions on the angular wiki for extending directives, I ended up with the following way to work around the issue, which I thought would add the correct md-accent class to all my input containers.

app.directive("mdAutocomplete", ["$window", function ($window) {

    "use strict";

    return {
        link: function (scope) {
            var containers = $window.document.getElementsByTagName("md-input-container");
            console.log(containers);
            console.log(containers.length);
            for(var i = 0; i < containers.length; i++){
                angular.element(containers[i]).addClass("md-accent");
            }
        }
    };


}]);

With this in place, I clearly see the output in my debugger that the directive extension is running, and finding the elements on the page. It finds both the following as it should:

0:md-input-container.md-icon-float.md-accent 1:md-input-container.ng-scope

What I don't understand is why it adds the md-accent class to the first, but not the second? The first md-input-container is by itself on the page, the 2nd is inside an md-auto-complete. I'm still new to angular and trying to figure out when this extension would be executed. Why wouldn't be able to append to both elements in the array, when it clearly found them both? What am I missing?


Solution

  • Since this is just working around a known bug, and I know the design of my site, I want the md-accent class on all md-input-containers. Here's what I did to work around the issue:

    .directive("mdInputContainer", [function () {
        "use strict";
        return {
            link: function (scope, element) {
                angular.element(element).addClass("md-accent");
            }
        };
    }]);
    

    Rather than try and modify the child md-input-container of the md-autocomplete, I found it easier to extend md-input-container itself, using the 2nd parameter of the link function to add the class. This now gives me a consistent look across all inputs wrapped in an input container