Angular:无法在我的 angular 指令中访问 element.bind 内的变量,因此我可以用它来操作 DOM

Angular: can't access a variable inside an element.bind in my angular directive so I can manipulate the DOM with it

我正在尝试编写一个指令,该指令 returns 一个布尔值,当用户在特定容器上滚动时为 true,当用户不滚动时为 false。我有这个工作是因为当我在我正在使用的 element.bind('scroll') 中抛出一个 console.log 时,我可以看到布尔值正确切换,但它不会影响相同的范围变量我在 element.bind 之外设置的名称。如果你看一下我放在一起的这个 JSFiddle,你就会看到这种情况的发生:https://jsfiddle.net/hurgledurf/bwyyL7mj/

这是我的指令代码:

(function() {
    'use strict';
    angular
        .module('myWebPage')
        .directive('scrollingDirective', scrollingDirective);

    function scrollingDirective() {
        var directive = {
            restrict: 'AE',
            link: link
        };
        return directive;

        function link (scope, element, attributes) {
            scope.actuallyScrolling = true;
            var timer;
            element.bind('scroll', function () {
                scope.actuallyScrolling = true;
                console.log('USER IS SCROLLING ', scope.actuallyScrolling);
                clearTimeout(timer);
                setTimeout(function () {
                    scope.actuallyScrolling = false;
                    console.log('INSIDE TIMER ', scope.actuallyScrolling);
                }, 1000);
            })
        }

    }
})(); 

这是一些基本的 HTML 我把它们放在一起作为示例:

<body ng-app="myWebPage">
  <div class="container" scrolling-directive>
    <p>
    scroll and check the console.log!
    Scrolling Boolean: {{actuallyScrolling}}
    </p>
  <div class="filler"></div>
  </div>
</body>

如果您查看 JS Fiddle,您可以看到 scope.actuallyScrolling 变量在 console.log 中打开和关闭,但在 DOM。这让我觉得存在某种我还没有弄清楚的范围界定问题,Angular 将它们视为两个独立的变量。有人对此有任何见解吗?谢谢你。

您可以使用scope.$apply()手动初始化scope更新:fiddle