body标签上ng-class内部的AngularJS工厂不起作用

问题描述 投票:3回答:2

被告知要创建服务/工厂并在全局控制器上使用它。这是我第一次听到全球控制器。无论如何,我创建了一个名为Scroll的工厂,并将其注入到main.controller.js中。工厂中的函数是isScrollingEnabled,它返回true或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中。

在此之前告诉我,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;
});
angularjs controller factory angular-services ng-class
2个回答
4
投票

您要为其附加值的控制器的$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 should-scroll>

0
投票

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

<body class="{{ scrollEnabled ? 'scrolling' : '' }}">
© www.soinside.com 2019 - 2024. All rights reserved.