2014-02-09 39 views
2

我想在AngularJS應用程序中設置一個onkeypress監聽器,以便能夠捕獲所有按鍵。這是在AngularJS中設置onkeypress偵聽器的正確方法嗎?

問題:

  • 這是正確的方式來實現,這是使用AngularJS?
  • 是否可以通過任何方式改進代碼,使其更符合AngularJS最佳實踐?

這是我使用的HTML代碼:

<html ng-app="moduleName"> 
    <body ng-controller="ControllerName" ng-keypress="keyPress($event)"> 
    </body> 
</html> 

這是JavaScript代碼:

var app = angular.module("moduleName", []); 
var ControllerName = function($scope) { 
    $scope.keyPress = function($event) { 
     // Logic goes here. 
    }; 
}; 

回答

1

通常,角應用已經有多個控制器,因此,您可能希望到: -

  1. 將keyPress方法設置爲在應用程序上的rootcope初始化(因爲你似乎希望這個方法在應用程序的任何地方從按鍵被調用。

    app.config(['$routeProvider', '$rootScope', 
        function ($routeProvider, $rootScope) { 
        $routeProvider.when('/Sample', { 
         templateUrl: 'views/Sample.html', 
         controller: 'sampleController' 
        }); 
    
        $routeProvider.otherwise({ redirectTo: '/app' }); 
        $rootScope.keypress = function($event) { 
         /* some code goes here */ 
        }; 
    }]); 
    
  2. 您還可以使用指令爲同樣的目的,這看起來像處理這種

    app.directive('listenToKeypress', function() { 
        return { 
        restrict: 'A', 
        link: function(scope, elem, attr, ctrl) { 
          elem.bind('keypress', function(e) { 
           /* do something here */ 
          }); 
        } 
        }; 
    }); 
    

和HTML更合適的方式可以是: -

<html ng-app="moduleName"> 
    <body ng-controller="ControllerName" listen-to-keypress> 
    </body> 
</html> 
相關問題