Angular指令窗口偏移表不起作用

时间:2015-09-14 13:50:55

标签: javascript angularjs angularjs-directive

我有这段代码:

.directive('sidenav', function ($window) {
        return {
            restrict: 'E',
            templateUrl: 'templates/side-nav.html',
            transclude: true,
            link: function($scope, element) {
                $scope.sidenavClass = "fixed";
                setInterval(function() {
                    console.log($window.pageYOffset);
                },1000);
                $scope.$watch(function() {
                    return $window.pageYOffset;
                }, function() {
                    console.log($window.pageYOffset);
                })
            }
        }
    })

当我滚动页面时,间隔控制台日志显示不同的值,但是手表不起作用,为什么?

1 个答案:

答案 0 :(得分:0)

You could just bind to the scrolling event of the window. Use apply since the event takes place outside of angular's digest cycle.

 angular.element($window).bind("scroll", function(e) {
   console.log('scroll')
   $scope.$apply(function() {
     console.log(e.pageYOffset)
   });
});