被告知创建服务/工厂并在全局 Controller 上使用它。这是我第一次听到全局 Controller 。不管怎样,我创建了一个名为 Scroll 的工厂并将其注入(inject)到我们的 main.controller.js 中。工厂中的函数 isScrollingEnabled 返回 true 或 false。另一个函数是 setScrolling ,它将把变量设置为 true 或 false。默认值设置为 true。
在主 Controller 内,我有这段代码
$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;
});
最佳答案
$scope
您附加值的 Controller 的值不会扩展到 <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>
关于AngularJS 工厂在 ng-class 内的 body 标签不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30473991/