AngularJS Directives why don't any class or style changes to children of the element apply?

278 views Asked by At

I'm currently using a directive for DOM changes for my application. I would like a button in element to hide on a state change.

HTML:

<div account layout="row" layout align="start center">
    <md-button id="accountIcon" class="md-icon-button">
        <md-icon aria-label="account" layout-align="center center">
            <i class="material-icons">account_circle</i>
        </md-icon>
    </md-button>

Directive:

angular.module("app")
.directive('account', ($document) => {
    return {
        restrict: 'A',
        link: (scope, element, attrs) => {
            scope.$on('hideAccount', () => {
                angular.element($document[0].querySelector('#accountIcon')).addClass('ng-hide);   
            });
        }
    };
});

The event is received and function is fired. The following also don't work.

angular.element(document.querySelector('#accountIcon')).addClass('ng-hide'); 
angular.element(document.querySelector('#accountIcon')).css('display', 'none'); 
angular.element(document.querySelector('#accountIcon')).addClass('hide'); 
var accountIcon = element.children()[0];
accountIcon.addClass('ng-hide');

where:

.hide {
    display: none;
}

Hopefully you get the gist. The following did work:

element.addClass('ng-hide')

Although obviously, I'm not looking to hide the entire element because there will be more buttons added soon. (not just an account icon). Any help or documentation appreciated. Thank you.

1

There are 1 answers

2
JLRishe On BEST ANSWER

Did you check the console for errors?

element.children()[0] is a DOM Node, which doesn't have an .addClass() method. To use the .addClass() method, just do this:

element.children().eq(0).addClass('ng-hide');

But the question remains - why are you going out of your way to use DOM manipulations when you don't have to? Couldn't you just use the ng-hide directive within your directive? Accessing elements by ID and doing all these DOM manipulations seems unnecessary.