angularjs - 将AngularJS中的文档级键事件绑定(bind)到特定路由/ Controller 的正确方法是什么?

标签 angularjs

我有一个打开画廊的单页应用程序。我只想在画廊打开时绑定(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/

相关文章:

javascript - 根据选择打印多个输入字段

javascript - .progress 没有看到 .error 中更新的范围值

javascript - Angular leaflet指令点击事件在移动设备上不起作用

javascript - 如何使用 $sce.trustAsHtml 在 trNgGrid 中显示 html 内容

javascript - 如何在 Angularjs 中模拟 HTML 表单请求?

angularjs - Observable.interval() + flatMap() 奇怪的行为

angularjs - 我想创建一个路由,以在用户登录时自动将用户重定向到主页

javascript - $http.get 过滤器 angularjs

angularjs - 为 jQuery UI 按钮创建 AngularJS 指令

javascript - Angular Moment - 使用自定义语言环境对象更改语言环境