AngularJS ng-class 内的工厂 body 标签不工作

AngularJS factory inside ng-class on body tag not working

被告知创建 service/factory 并在全局控制器上使用它。这是我第一次听到全局控制器。无论如何,我创建了一个名为 Scroll 的工厂并将其注入我们的 main.controller.js。工厂中的函数是 isScrollingEnabled returns true or false。另一个函数是 setScrolling,它将变量设置为 true 或 false。默认值设置为 true。

在主控制器里面,我有这段代码

$scope.scrollEnabled = Scroll.isScrollingEnabled();
console.log('value of $scope.scrollEnabled', $scope.scrollEnabled);

该代码在控制台中显示为 true,这很好。

在我的模板上,我就是这样使用的。我有将滚动设置为 false 的按钮。控制台中的值吐出 false 这很好。

<body ng-class="{ 'scrolling' : scrollEnabled }">

但是,它不起作用。如果我把它改成下面写的代码,就可以了

<body ng-class="{ 'scrolling' : false }">

所以我猜,它不在范围内,尤其是 ui-view 在 index.html 中,main.controller.js 和 main.html 将加载到 ui-view 中。 < body > 在此之前告诉我,main.controller.js 内的任何范围在 ui-view.

之外都不起作用

那么解决这个问题的方法是什么?

抱歉没有发布工厂。在这里

  .factory('Scroll', function() {

    var scrollEnabled = true; // i then changed it to false hoping it will work, it didn't

    var ScrollEvent = {
      isScrollingEnabled: function () {
        return scrollEnabled;
      },
      disablePageScrolling: function() {
        scrollEnabled = false;
      }
    };

    return ScrollEvent;
});

您要附加值的控制器的 $scope 不会扩展到 <body> 元素。相反,您可以组合一个指令:

.directive('shouldScroll', function (Scroll) {
  return {
    restrict: 'A',
    link: function ($scope, elem) {
      $scope.$watch(Scroll.isScrollingEnabled, function (n) {
        if (n) {
          elem.addClass('scrolling');
        } else if (n === false) {
          elem.removeClass('scrolling');
        }
      });
    }
  };
});

您可以像这样将其附加到 body:

<body should-scroll>

另一种在某些情况下有效的解决方案是使用 class 而不是 ng-class:

<body class="{{ scrollEnabled ? 'scrolling' : '' }}">