我有一个打开画廊的单页应用程序。我只想在画廊打开时绑定(bind)文档级别的 keyup 事件(用于键盘画廊控件),即。当路线匹配时
.when('/reference/:galleryId/:imageId/', { templateUrl: '/partials/gallery.htm', controller: 'galleryController', controllerAs: 'reference' })
当我离开这条路线时,我想解开它。
可能是一个问题的一件事是,我阻止在同一个画廊中重新加载图像之间的 View :
.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
var original = $location.path;
$location.path = function (path, reload) {
if (reload === false) {
var lastRoute = $route.current;
var un = $rootScope.$on('$locationChangeSuccess', function () {
$route.current = lastRoute;
un();
});
}
return original.apply($location, [path]);
};
}])
Demo(点击“Fotografie”打开图库)
http://tr.tomasreichmann.cz/
Angular 奇才来救援?
感谢您的时间和精力
最佳答案
您可以将 keyup 事件绑定(bind)到 $document
在 Controller 的构造函数中,然后在 Controller 的 $scope
时取消绑定(bind)事件被摧毁。例如:
.controller('galleryController', function ($scope, $document) {
var galleryCtrl = this;
function keyupHandler(keyEvent) {
console.log('keyup', keyEvent);
galleryCtrl.keyUp(keyEvent);
$scope.$apply(); // remove this line if not need
}
$document.on('keyup', keyupHandler);
$scope.$on('$destroy', function () {
$document.off('keyup', keyupHandler);
});
...
});
当 View 变为非事件状态时,不会留下任何东西。
如果您觉得在 Controller 中执行此操作不正确,您可以将其移动到自定义指令中并将其放置在 View 的模板中。
关于angularjs - 将AngularJS中的文档级键事件绑定(bind)到特定路由/ Controller 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25018422/