0

I'm trying to manipulate an element class within a directive. The directive is of a toolbar and it's supposed to add a class to 2 elements after some scroll.

  1. The element directive itseld;
  2. The view, to add/remove margin;

This is my html structure:

<ag-toolbar class="ag-toolbar--sec"></ag-toolbar>
<div ui-view="app" autoscroll="false" id="appView"></div>

And this is my directive:

function agToolbar($window) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            var elView;
            setTimeout(function(){ 
                elView = document.getElementById("appView");
            }, 400);

            angular.element($window).bind("scroll", function() {
                if (this.pageYOffset >= 128) {
                    element.addClass('scroll');
                    elView.addClass('agMargin');
                } else {
                    element.removeClass('scroll');
                    elView.removeClass('agMargin');
                };
            });
        }
    };
}

In the console I keep getting the error:

elView.addClass is not a function

elView.removeClass is not a function

But the element.addClass is working fine. Any ideas why?

1 Answer 1

4

addClass belongs to jqLite (or jQuery if available), see https://docs.angularjs.org/api/ng/function/angular.element.

That is, you need to wrap the DOM element in a jqLite/jQuery element:

elView = angular.element(document.getElementById("appView"));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! It worked. Didn't knew about it, and since the console was showing the dom correctly, i didn't knew what to do.
@CelsomTrindade Side question: why are you using setTimeout()? Whatever you're trying to achieve, it's quite dangerous, e.g. if the user scrolls before elView has been set.
I was still testing. But when I try to get the element (which is a ngView) it's still not loaded. Any way to fix this?
What if you put the <ag-toolbar /> below the <div /> rather than above?
Then the layout will not be as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.