javascript - 更新 Angular Directive(指令)中的数据

标签 javascript jquery angularjs angularjs-directive

我在获取传递给指令以在 DOM 更新时进行更新的数据时遇到问题。该指令突出显示侧导航上与页面上滚动到的位置相关的事件选项卡。这是fiddle example我所做的事情。

在我的本地站点上,有很大一部分可以有条件地显示或隐藏,并且用户可以并且可能经常更改此设置。因此,这会更改我存储在 resultsSections 中的元素 ID 的位置。当位置发生变化时,它们不会在指令中更新。

<script type="text/javascript">
$scope.getResultsSectionPosition = function () {
    var resultsSections = {};
    $('.results-heading').each(function () {
        resultsSections[this.parentNode.id] = $(this).offset().top;
    });
    console.log(resultsSections);
    return $scope.resultsSections = resultsSections;
}
$scope.getResultsSectionPosition();
</script>

我已通过调用 $scope.getResultsSectionPosition() 重新初始化了本地站点 - 新的偏移量存储在 resultsSections 中,但指令仍保留初始值。 如何强制指令使用最活跃的数据?

myApp.directive('navActive', function () {
return function(scope, element, attrs) {

        var height = $(window).height(),
            section = 0;
        $(window).bind("scroll", function() {
            var position = $(this).scrollTop();
            for (section in scope.resultsSections) {
                if (position + height - 50 >= scope.resultsSections[section]) {
                    $('li').removeClass('results-nav-active');
                    $('#nav_' + section).addClass('results-nav-active');
                };
            };
        });
    };  
})

我尝试过使用 scope.$watch('resultsSections", function(){...}) 但没有成功。

最佳答案

你应该能够使用$watch,但你也可以使用isolatescope属性,然后将你的控制$scope变量直接传递给你的指令

我稍微调整了你的代码,并添加了一些 console.log 以查看发生了什么,你可以在这里看到它 http://jsfiddle.net/DotDotDot/uC2dP/14/

我在顶部添加了一个按钮,强制修改位置,以便查看指令中的影响,并在指令中添加了一个 console.log() ,其中包含滚动时调用的位置。此外,您的指令现在具有独立的范围,resultsSections 绑定(bind)到 HTML 中给出的参数

return {
    scope:{resultsSections:"=sections"},
    link:function(scope, element, attrs) {


    var height = $(window).height(),
        section = 0;
    $(window).bind("scroll", function() {
        var position = $(this).scrollTop();
        console.log(scope.resultsSections)
        for (section in scope.resultsSections) {
            if (position + height - 50 >= scope.resultsSections[section]) {
                $('li').removeClass('results-nav-active');
                $('#nav_' + section).addClass('results-nav-active');
            };
        };
    });
}
}

在 HTML 中:

<section nav-active sections="resultsSections">

您可以看到,如果单击按钮然后滚动,指令中的位置就会正确更新

玩得开心

关于javascript - 更新 Angular Directive(指令)中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17950473/

相关文章:

javascript - 使用 angularjs $resource 从 Web api 调用自定义方法

javascript - 在 JavaScript 中从数组到序列

javascript html标签不添加内容

jquery - Instagram 将幻灯片放映到网站中

基于单选的AngularJS过滤器

javascript - Angularjs ng-model 未绑定(bind)到隐藏输入

javascript - 根据输入字段中的文本隐藏/显示 div 元素

javascript - bpopup jQuery 不工作

javascript - 这是什么 JQuery 脚本?

javascript - 错误 : Uncaught (in promise): Error: Cannot match any routes RC4 Child Routes