简体   繁体   中英

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

I'm trying to write a directive that returns a boolean that is true when the user is scrolling on a specific container, and false when they are not scrolling. I have this working in that I can see Boolean toggling properly when I throw a console.log inside the element.bind('scroll') I'm using, but it's not affecting the scope variable of the same name I set outside of the element.bind. You can see this happening if you take a look at this JSFiddle I threw together: https://jsfiddle.net/hurgledurf/bwyyL7mj/

This is the code I have for the directive:

(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);
            })
        }

    }
})(); 

And this is some basic HTML I threw together as an example:

<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>

If you take a look at the JS Fiddle, you can see that the scope.actuallyScrolling variable toggles on and off in the console.log, but doesn't change on the DOM. This makes me thing that there's some sort of scoping issue going on that I haven't figured out, and Angular is treating them as two separate variables. Anyone have any insight into this? Thank you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM