javascript - 如何使 AngularJS 链接可通过单击或 Enter 键使用

标签 javascript angularjs

我正在使用 AngularJS,并且有一个用于输入的文本框和两个使用该输入转到不同 URL 的按钮。现在,我正在为他们使用 ng-click 。这对于单击按钮来说效果很好,但是如果我按 Tab 到按钮并按 enter,则不会发生任何情况。

网上的其他结果建议使用 ng-submit,但这是表单的属性而不是按钮的属性(我认为),因此它不适用于两个按钮。

关于如何让它同时使用鼠标和 Tab 键并按 Enter 键工作,有什么建议吗?

谢谢!

最佳答案

直接从源头开始,看起来您也可以使用 ng-keyup 并检查它是否是一个 Enter,然后执行您的操作,但我认为编写一个自定义指令,这样您就不必在 View 定义仍然会让事情变得更容易。

这是 ng-click 等的来源

/**
 * @ngdoc directive
 * @name ng.directive:ngClick
 *
 * @description
 * The ngClick allows you to specify custom behavior when
 * element is clicked.
 *
 * @element ANY
 * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
 * click. (Event object is available as `$event`)
 *
 * @example
   <doc:example>
     <doc:source>
      <button ng-click="count = count + 1" ng-init="count=0">
        Increment
      </button>
      count: {{count}}
     </doc:source>
     <doc:scenario>
       it('should check ng-click', function() {
         expect(binding('count')).toBe('0');
         element('.doc-example-live :button').click();
         expect(binding('count')).toBe('1');
       });
     </doc:scenario>
   </doc:example>
 */
/*
 * A directive that allows creation of custom onclick handlers that are defined as angular
 * expressions and are compiled and executed within the current scope.
 *
 * Events that are handled via these handler are always configured not to propagate further.
 */
var ngEventDirectives = {};
forEach(
  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress'.split(' '),
  function(name) {
    var directiveName = directiveNormalize('ng-' + name);
    ngEventDirectives[directiveName] = ['$parse', function($parse) {
      return function(scope, element, attr) {
        var fn = $parse(attr[directiveName]);
        element.bind(lowercase(name), function(event) {
          scope.$apply(function() {
            fn(scope, {$event:event});
          });
        });
      };
    }];
  }
);

http://code.angularjs.org/1.1.5/angular.js

根据上面的代码为你画了一个 fiddle :

http://jsfiddle.net/Yd8rh/2/

Javascript

angular.module("myApp", []).directive("actionDirective", ['$parse', function($parse) {
      return function(scope, element, attr) {
        //grabbing the function from the attributes and parsing it (to get parameters I believe, this taken from the code above.
        var fn = $parse(attr['actionDirective']);

        //making the handler so it can be bound to different events without repeating again taken from source above
        var handler = function(event) {
            scope.$apply(function() {
             fn(scope, {$event:event});
            }
          )};

         //If clicked calling the handler
         element.bind('click', handler);
         //Checking first that it's the enter key "13" then calling the handler
         element.bind('keyup', function(event) { if(event.keyCode==13) handler(event)});
      }
}]).controller("MyCtrl", function($scope){
    $scope.somethingHappened = function() {
        alert("something happened");
    }
});

HTML

<div ng-app="myApp" ng-controller="MyCtrl">
    <button action-directive="somethingHappened()">Test</button>
</div>

一如既往地在这样做中学到了一些东西。在 Chrome 和 Firefox 中(至少在 Ubuntu 上),空格键似乎是作为点击事件出现的,在 Chrome 中似乎也是如此,但在 Firefox 中则不然。只是认为这是一种有趣的小差异,并惊讶地看到空格键和 Enter 键记录为鼠标单击事件。

关于javascript - 如何使 AngularJS 链接可通过单击或 Enter 键使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17689800/

相关文章:

javascript - 以有组织的方式支持新浏览器

angularjs - 测试在 $compile 期间更改 HTML 节点元素的指令

angularjs - 如何在 Jasmine for AngularJS 中对表单有效/无效进行单元测试?

angularjs - 如果为空,则将 md-chips 输入字段边框变为模糊红色

javascript - 像 twitter 一样的字幕褪色 + steamlessly?

javascript - 使用 event.dataTransfer.setData 从浏览器拖出多个文件到桌面

javascript - 获取对象 ES6 中数组的总数/长度

javascript - jQuery $.getJSON 不工作

angularjs - Ngmessages Uncaught TypeError l.module(...).info 不是函数

javascript - AngularJS NG重复: limitTo not limiting object loop