绑定窗口滚动AngularJS方式

Bind window scroll the AngularJS way

本文关键字:方式 AngularJS 滚动 窗口 绑定      更新时间:2023-09-26

AngularJS新手,这里有jQuery背景。使用AngularJS,我试图开发一个固定顶部导航栏,其背景在窗口滚动时从透明过渡到不透明。但是,我在将窗口滚动绑定到$scope时遇到了问题。

以下是到目前为止我所拥有的不起作用的东西:

http://jsfiddle.net/brettwick86/pt33te3z/3/

function bgScroll($scope) {
  angular.element(window).bind('scroll', function () {
    $scope.scroll = window.pageYOffset;
    $scope.height = document.getElementById('main-header').offsetHeight;
    $scope.a = $scope.scroll / $scope.height;
    $scope.bgColor = 'rgba(0,0,0,' + $scope.a + ')';
  });
}

视图:

<div ng-controller="bgScroll">
  <nav class="navbar navbar-inverse navbar-bw navbar-fixed-top" role="navigation" style="background-color: {{ bgColor }};">
    ...
  </nav>
</div>

非常感谢您的帮助!

angular.element委托给jQuery(如果包含)或JQlite,这意味着回调函数不会自动将更改应用于$scope

function bgScroll($scope) {
  angular.element(window).bind('scroll', function () {
    $scope.scroll = window.pageYOffset;
    $scope.height = document.getElementById('main-header').offsetHeight;
    $scope.a = $scope.scroll / $scope.height;
    $scope.bgColor = 'rgba(0,0,0,' + $scope.a + ')';
    // Apply the changes to the scope here
    $scope.$apply();
  });
}

您应该避免在控制器中进行dom操作。相反,创建一个新指令并在那里执行。

enter code here

<div bg-scroll ng-controller="bgScroll">
  <nav class="navbar navbar-inverse navbar-bw navbar-fixed-top" role="navigation" style="background-color: {{ bgColor }};">
    ...
  </nav>
</div>   
myapp.directive('bgScroll', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            angular.element(window).bind('scroll', function () {
               scope.scroll = window.pageYOffset;
               scope.height = document.getElementById('main-header').offsetHeight;
               scope.a = scope.scroll / scope.height;
               scope.bgColor = 'rgba(0,0,0,' + scope.a + ')';
            });
scope.$on('$destroy', function() {
        angular.element(window).unbind('scroll');
      });
        }
    };
});