AngularJS 自定义指令和控制器方法不起作用,并且在 Chrome 浏览器中无法到达断点

问题描述 投票:0回答:1

AngularJS 自定义指令和控制器方法附加到 md-fab 滚动返回顶部按钮。当页面向下滚动时,md-fab 按钮就会变得可见,并在页面到达顶部时隐藏。 我的问题是自定义指令不起作用,因此向下滚动时 md-fab 按钮不可见。如果我将 md-button css 属性可见性更改为可见并向下滚动页面,则单击 md-fab 按钮不会响应滚动回页面顶部。

我开始面临这个问题,因为我只重新整理了index.html 文件中相同的工作代码。

我几天都无法追踪这个问题。感谢一些专家指导来解决这个问题,告诉我哪里出了问题。

mainCtrl方法

(function() {
  angular.module('mainApp')
  .controller('mainCtrl', function($scope, $window) {
    $scope.scrollTop = function () {
      $window.scrollTo(0, 0);
    };
  } 
})();

自定义指令

(function() {
  angular
  .module("mainApp")
  .directive("scrollToTop", function ($window) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
      angular.element($window).bind("scroll", function() {
        if (this.pageYOffset > 0) {
          element.css({visibility: 'visible'});
        } else {
          element.css({visibility: 'hidden'});
        }
      });
     }
   }
 });
})();

HTML

<body layout="row" ng-controller="mainCtrl" ng-cloak>
  <md-sidenav>
  </md-sidenav>
  <main layout="column" flex aria-hidden="false">
    <md-toolbar layout-padding class="app-toolbar">
    </md-toolbar>
    <md-content md-scroll-y flex>
      <div ui-view flex="noshrink" ng-hide="data.error">
      </div>
      <div flex="noshrink" ng-show="data.error">
      </div>
      <button 
      type="button" 
      class="md-fab md-fab-bottom-right md-button md-ink-ripple" 
      draggable scroll-to-top 
      ng-click="scrollTop()" 
      style="position: fixed; visibility: hidden;" aria-label="Back to   Top">
        <md-tooltip>Draggable Scroll Back to Top</md-tooltip>
        <md-icon md-svg-src="img/material/ic_expand_less-24px.svg" aria-hidden="scrollBackToTop button">
        </md-icon>
      </button>
    </md-content>
  </main>
</body>`
angularjs methods directive
1个回答
0
投票

未经测试,我认为 mainController 中的 $scope 无法向下滚动到顶部,因此它找不到调用 ng-click 的方法。因此,为什么当你重新洗牌你的index.html时它就停止工作了

相反,您可以尝试给滚动到顶部它自己的控制器,并隔离其范围

(function() {
  angular
  .module("mainApp")
  .directive("scrollToTop", function ($window) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
      angular.element($window).bind("scroll", function() {
        if (this.pageYOffset > 0) {
          element.css({visibility: 'visible'});
        } else {
          element.css({visibility: 'hidden'});
        }
      });
     },
     // ==== give scrollToTop its own controller: ====
     controller: function($scope, $window) {
      $scope.scrollTop = function () {
        $window.scrollTo(0, 0);
      };
    },
    scope: {} // ==== Give scrollToTop its own isolated scope for clarity ====
   }
 });
})();
© www.soinside.com 2019 - 2024. All rights reserved.