Search code examples
jqueryangularjsangular-directive

AngularJS directive DOM manipulation does not work


This code have to scroll slowly on the page. I am using AngularJS 1.4 and I have a problem with code integration.

More exactly, if I make a simple JS source file with this code, it works very good, without problems. But I read that DOM manipulation have to stay in directive. The problem is that if I am integrating in my directive using link function(scope, element, attrs), my code will not work properly.

I tried to put it in angular.run() function and in angular.controller() function, but with same side effect.

How may I integrate this code in my angular structure?

PS: This code have to run before another processing.

function changeActiveMenu(targetTag) {
    var rmClass = $('[name="li-menu"]');
    var addClass = $('#' + targetTag);
    rmClass.removeClass('active');
    addClass.addClass('active');
}

function scrollToTag(targetTagId) {
        var targetTag = $('[id="'+ targetTagId +'"]');
        $('html, body').animate({ scrollTop: targetTag.offset().top }, 'slow');
}

$window.onload = function () {
    $('[name=home-page]').click(function(){
        scrollToTag('home');
        changeActiveMenu('li-home-page');
    });
    $('[name=search-sal]').click(function(){
        scrollToTag('search-for-salaries');
        changeActiveMenu('li-search-sal');
    });

    $(window).bind("scroll", function() {
        var sec1 = $("#home").offset().top;
        var sec2 = $("#search-for-salaries").offset().top - 300;

        if ($(this).scrollTop() >= sec1){ 
            changeActiveMenu('li-home-page'); 
        }
        if ($(this).scrollTop() >= sec2){ 
            changeActiveMenu('li-search-sal'); 
        }
    });

    $('.chgCursor').on('mouseover', function () {
        $(this).addClass('cursor-pointer');
    });
    $('.chgCursor').on('mouseout', function () {
        $(this).removeClass('cursor-pointer');
    });

    console.log(element);
};

Solution

  • I figured out.

    I had to make a bind for click event.

    $(window).bind("click", function(e) {
        switch(e.target.name) {
            case "home-page":
            scrollToTag('home');
            changeActiveMenu('li-home-page');
                break;
            case "search-sal":
            scrollToTag('search-for-salaries');
            changeActiveMenu('li-search-sal');
                break;
        }
    });