将AngularJS中的文档级键事件绑定到特定路由/控制器的正确方法是什么?

Tom*_*Tom 5 angularjs

我有一个单页应用程序可以打开一个库.我想仅在图库打开时绑定文档级别键盘事件(用于键盘库控件),即.当路线匹配时

.when('/reference/:galleryId/:imageId/', { templateUrl: '/partials/gallery.htm', controller: 'galleryController', controllerAs: 'reference' })
Run Code Online (Sandbox Code Playgroud)

当我离开这条路线时,我想解开它.

可能有问题的一件事是,我阻止在同一个图库中的图像之间重新加载视图:

.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]);
    };
}])
Run Code Online (Sandbox Code Playgroud)

演示(点击"Fotografie"打开画廊) http://tr.tomasreichmann.cz/

Angular wiz救援?

感谢您的时间和精力

run*_*arm 7

您可以将keyup事件绑定到$document控制器的构造函数中,然后在控制器$scope被销毁时取消绑定事件.例如:

.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);
  });

  ...
});
Run Code Online (Sandbox Code Playgroud)

当视图变为非活动状态时,将不会遗留任何内容.

如果您觉得在控制器中执行此操作是不对的,可以将其移动到自定义指令中并将其放在视图的模板中.