【问题标题】:How can I detect keydown or keypress event in angular.js?如何检测 angular.js 中的 keydown 或 keypress 事件?
【发布时间】:2013-08-23 23:43:58
【问题描述】:

我正在尝试获取手机号码文本框的值,以使用 angular.js 验证其输入值。我是使用 angular.js 的新手,不太确定如何实现这些事件并放置一些 javascript 来验证或操作我的 html 代码中的表单输入。

这是我的 HTML:

    <div>
        <label for="mobile_number">Mobile Number</label>
        <input type="text" id="mobile_number" placeholder="+639178983214" required
           ngcontroller="RegisterDataController" ng-keydown="keydown">
    </div> 

还有我的控制器:

    function RegisterDataController($scope, $element) {
       console.log('register data controller');
       console.log($element);
       $scope.keydown = function(keyEvent) {
        console.log('keydown -'+keyEvent);
       };
    }

我不知道如何在 angular.js 中使用 keydown 事件,我也搜索了如何正确使用它。我可以验证我对指令的输入吗?或者我应该像我所做的那样使用控制器来使用 keydown 或 keypress 之类的事件?

【问题讨论】:

    标签: html twitter-bootstrap angularjs angularjs-directive


    【解决方案1】:

    更新:

    ngKeypressngKeydownngKeyup 现在是 AngularJS 的一部分。

    <!-- you can, for example, specify an expression to evaluate -->
    <input ng-keypress="count = count + 1" ng-init="count=0">
    
    <!-- or call a controller/directive method and pass $event as parameter.
         With access to $event you can now do stuff like 
         finding which key was pressed -->
    <input ng-keypress="changed($event)">
    

    在这里阅读更多:

    https://docs.angularjs.org/api/ng/directive/ngKeypress https://docs.angularjs.org/api/ng/directive/ngKeydown https://docs.angularjs.org/api/ng/directive/ngKeyup

    早期的解决方案:

    解决方案 1:使用 ng-changeng-model

    <input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
    ng-controller="RegisterDataController" ng-change="keydown()">
    

    JS:

    function RegisterDataController($scope) {       
       $scope.keydown = function() {
            /* validate $scope.mobileNumber here*/
       };
    }
    

    解决方案 2. 使用$watch

    <input type="text" placeholder="+639178983214" ng-model="mobileNumber" 
    ng-controller="RegisterDataController">
        
    

    JS:

    $scope.$watch("mobileNumber", function(newValue, oldValue) {
        /* change noticed */
    });
    

    【讨论】:

    • 使用迄今为止的最新稳定版本 (1.0.8)
    【解决方案2】:

    您可以查看 Angular UI @http://angular-ui.github.io/ui-utils/,它提供了用于检测 keydown、keyup、keypress 的详细事件句柄回调函数 (还有 Enter 键、退格键、alter 键、控制键)

    <textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
    <textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
    <textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
    <textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
    

    【讨论】:

      【解决方案3】:

      您的“ng-keydown”属性输入正确,但您错过了一个简单的步骤。仅仅因为您将 ng-keydown 属性放在那里,并不意味着 Angular 知道如何处理它。这就是“指令”发挥作用的地方。您正确使用了该属性,但是您现在需要编写一个指令,该指令将告诉 Angular 当它在 html 元素上看到该属性时要做什么。

      以下是您将如何执行此操作的示例。我们将把指令从 ng-keydown 重命名为 on-keydown(以避免违反 here 的“最佳实践”):

      var mod = angular.module('mydirectives');
      mod.directive('onKeydown', function() {
          return {
              restrict: 'A',
              link: function(scope, elem, attrs) {
                   // this next line will convert the string
                   // function name into an actual function
                   var functionToCall = scope.$eval(attrs.ngKeydown);
                   elem.on('keydown', function(e){
                        // on the keydown event, call my function
                        // and pass it the keycode of the key
                        // that was pressed
                        // ex: if ENTER was pressed, e.which == 13
                        functionToCall(e.which);
                   });
              }
          };
      });
      

      指令 simple 告诉 Angular,当它看到一个名为“ng-keydown”的 HTML 属性时,它应该监听具有该属性的元素并调用传递给它的任何函数。在 html 中,您将拥有以下内容:

      <input type="text" on-keydown="onKeydown">
      

      然后在您的控制器中(就像您已经拥有的一样),您将向控制器的范围添加一个名为“onKeydown”的函数,如下所示:

      $scope.onKeydown = function(keycode){
          // do something with the keycode
      }
      

      希望对您或其他想了解的人有所帮助

      【讨论】:

      • 指令名称不会是 'ng-keydown' 吗?
      • 正如here 解释的那样,指令名称是标准化的。这意味着如果您希望您的 html 属性为ng-my-attribute,您可以将指令名称写为'ngMyAttribute。每个大写字母都将小写并以- 开头。这在 javascript 中很常见,因为它允许将连字符字符串用作 javascript 对象中的键。
      • 你不应该用 ng 前缀来命名你的指令。对于有角度的书面指令,这是“保留的”。但是,最好使用您自己的前缀。
      • 确实如此。我只是想让它变得简单,但我会编辑答案以避免任何混淆。
      【解决方案4】:

      使用 ng-controller 的 JavaScript 代码:

      $scope.checkkey = function (event) {
        alert(event.keyCode);  //this will show the ASCII value of the key pressed
      

      }

      在 HTML 中:

      <input type="text" ng-keypress="checkkey($event)" />
      

      您现在可以使用 keyCode 方法放置支票和其他条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-24
        相关资源
        最近更新 更多