gpt4 book ai didi

javascript - 使 Angular 功能可供所有 Controller 使用

转载 作者:行者123 更新时间:2023-11-28 19:30:37 25 4
gpt4 key购买 nike

我目前在 Angular 的 app.run(function... 中拥有一些关键功能代码:

app.run(function($rootScope, $window) {

//window dimensions
$window.width = angular.element($window).width();
$window.height = angular.element($window).height();

//initial variables
var scrollTimer = false;

//keydown event listeners
document.onkeydown = function(e){

//scroll down keys
if (e.keyCode == 32 || e.keyCode == 40) {
scroll(-1);
e.preventDefault(); }

//scroll up keys
if (e.keyCode == 38) {
scroll(1);
e.preventDefault(); }
}

//scroll
function scroll(delta){

//check scroll timer
if (scrollTimer) return;

//new scroll pane
if (delta < 0 && $rootScope.pane.count < $rootScope.pane.max) $rootScope.pane.count += 1;
else if (delta > 0 && $rootScope.pane.count > 0) $rootScope.pane.count -= 1;
else return;

//apply current pane
$rootScope.$apply();

//animate scroll
var scroll = $rootScope.pane.count * $window.height + "px";
$("html, body").animate({scrollTop: scroll}, 600, "swing");

//reset scroll timer
scrollTimer = true;
setTimeout(function(){ scrollTimer = false; }, 1500);
}

});

现在我有一个 Controller (可能还有其他 Controller ),我想在其中访问 scroll() 函数。就像这样:

app.controller("AsideCtrl", function($rootScope, $scope){ 

//button scrolling
$scope.scrollTo = function(index){
index = index + 1;
scroll(index);
}

});

当然,由于$scope,这不起作用。有没有简单的方法可以实现这一点?

最佳答案

您可以使用 Angular 提供程序,您可以在此处找到文档 https://docs.angularjs.org/guide/providers 。因此,您可以使提供程序具有您的功能滚动并将提供程序传递给您的 Controller 。

示例:http://jsfiddle.net/7xvzm7b7/

var myApp = angular.module('myApp', []);

myApp.service('$scrollService', function() {
this.scroll = function(delta){
//check scroll timer
if (scrollTimer) return;

//new scroll pane
if (delta < 0 && $rootScope.pane.count < $rootScope.pane.max) $rootScope.pane.count += 1;
else if (delta > 0 && $rootScope.pane.count > 0) $rootScope.pane.count -= 1;
else return;

//apply current pane
$rootScope.$apply();

//animate scroll
var scroll = $rootScope.pane.count * $window.height + "px";
$("html, body").animate({scrollTop: scroll}, 600, "swing");

//reset scroll timer
scrollTimer = true;
setTimeout(function(){ scrollTimer = false; }, 1500);
}
return this;
});
//scroll

myApp.controller('ctrl', ['$scope', '$scrollService', function($scope, $scrollService) {
$scrollService.scroll();
}]);

关于javascript - 使 Angular 功能可供所有 Controller 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26882350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com