Patrik Beck
Patrik Beck

Reputation: 2505

Using "this" in ng-class expression

I am trying to use 'this' in ng-class condition, but it doesn't work.

I am essentially trying this:

<div class=".." ng-class="{hidden: $(this).find(..).hasClass('trigger')}">
</div>

I would like AngularJS to apply the class 'hidden' based on the presence of a different class on a nested element.

Should I move the complex code to the controller? How can I reference the element ng-class is being defined on?

Regards!

Upvotes: 1

Views: 309

Answers (2)

Huston Hedinger
Huston Hedinger

Reputation: 511

In this case you probably want to create a custom directive. A good rule of thumb is that you should not do dom manipulation directly from a controller. In your case a custom directive would look like this:

...
.directive('applyTrigger', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var triggerEl = element.find(..);
            scope.$watch(function() {
                return triggerEl.attr('class'); }, 
                function(newValue){
                    if(triggerEl.hasClass('trigger')) {
                        element.addClass('hidden');
                    } else {
                        element.removeClass('hidden');
                    }

                });

        };
    }
});

And then you could use it on the parent div:

<div class=".." applyTrigger>
</div>

Give this a try and let me know what you find!

Upvotes: 1

9ers Rule
9ers Rule

Reputation: 164

You should use the controller to tell you if you should set a ng-class.

<div class=".." ng-class="{hidden: {{showthisdiv}}}">
</div>

Then in the controller set the showthisdiv.

Upvotes: 0

Related Questions