将javascript函数转换为angularjs指令

时间:2017-05-10 12:24:44

标签: javascript angularjs

我想在custome指令my angularjs app中使用bellow javascript函数。如何将thi javascript函数转换为angularjs custome指令?

我使用了演示jsfiddle

function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#navPills li').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
        $('#navPills ul li').removeClass("active");
        currLink.addClass("active");
    }
    else{
        currLink.removeClass("active");
    }
});
}

修改

我试过了,

app.directive('scrollSpy', function($timeout) {
return {
    restrict: 'A',
    link: function(scope, elem, attr) {
        var offset = parseInt(attr.scrollOffset, 10)
        if(!offset) offset = 10;
         var scrollPos = offset;
        $('#navPills li').each(function () {
            var currLink = $(this);
            var refElement = $(currLink.attr("href"));
            if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
                $('#navPills ul li').removeClass("active");
                currLink.addClass("active");
            }
            else{
                currLink.removeClass("active");
            }
        });
    }
}
});

及其显示错误Cannot read property 'top' of undefined

0 个答案:

没有答案