仅使用键盘导航UI

时间:2013-06-30 07:02:33

标签: angularjs navigation keypress angular-ui

我正在尝试仅使用键盘浏览记录列表。当页面加载时,默认的“焦点”应该在第一条记录上,当用户单击键盘上的向下箭头时,需要关注下一条记录。当用户单击向上箭头时,应该关注先前的记录。当用户单击Enter按钮时,它应该将它们带到该记录的详细信息页面。

Here's what I have so far on Plunkr.

在1.1.5(不稳定)中AngularJS似乎支持这一点,我们不能在生产中使用它。我目前正在使用1.0.7。我希望做这样的事情 - 密钥应该在文档级别处理。当用户按下某个键时,代码应该在允许的键数组中查找。如果找到匹配(例如向下键代码),它应该移动焦点(将.highlight css应用)到下一个元素。当按下enter时,它应该抓取.highlight css的记录并获取记录ID以供进一步处理。

谢谢!

5 个答案:

答案 0 :(得分:14)

以下是您可以选择的示例: http://plnkr.co/edit/XRGPYCk6auOxmylMe0Uu?p=preview

<body key-trap>
  <div ng-controller="testCtrl">
    <li ng-repeat="record in records">
      <div class="record"
           ng-class="{'record-highlight': record.navIndex == focu sIndex}">
        {{ record.name }}
      </div>
    </li>
  </div>
</body>

这是我能想到的最简单的方法。 它将指令keyTrap绑定到捕获body事件的keydown 向子范围发送$broadcast消息。 元素持有者范围将捕获消息并简单地递增或递减 如果点击open,则focusIndex或触发enter函数。

修改

http://plnkr.co/edit/rwUDTtkQkaQ0dkIFflcy?p=preview

现在支持,有序/过滤列表。

事件处理部分尚未更改,但现在使用$index并过滤了列表缓存 技术结合起来跟踪哪个项目正在集中。

答案 1 :(得分:5)

到目前为止提供的所有解决方案都有一个共同的问题。指令不可重用,它们需要知道在控制器提供的父$ scope中创建的变量。这意味着如果你想在不同的视图中使用相同的指令,你需要重新实现你以前的控制器所做的一切,并确保你使用相同的变量名,因为指令基本上有硬编码的$ scope变量名在他们中。您肯定无法在同一父范围内两次使用相同的指令。

解决这个问题的方法是在指令中使用隔离范围。通过执行此操作,您可以通过一般地参数化父作用域所需的项目来使指令可重用,而不管父作用域。

在我的解决方案中,控制器唯一需要做的是提供一个selectedIndex变量,该变量指令用于跟踪当前选中表中的哪一行。我可以将此变量的责任隔离到指令,但是通过使控制器提供变量,它允许您操作指令外的表中当前选定的行。例如,您可以在控制器中实现“单击选择行”,同时仍然使用箭头键在指令中进行导航。

指令:

angular
    .module('myApp')
    .directive('cdArrowTable', cdArrowTable);
    .directive('cdArrowRow', cdArrowRow);

function cdArrowTable() {
    return {
        restrict:'A',
        scope: {
            collection: '=cdArrowTable',
            selectedIndex: '=selectedIndex',
            onEnter: '&onEnter'
        },
        link: function(scope, element, attrs, ctrl) {
            // Ensure the selectedIndex doesn't fall outside the collection
            scope.$watch('collection.length', function(newValue, oldValue) {
                if (scope.selectedIndex > newValue - 1) {
                    scope.selectedIndex = newValue - 1;
                } else if (oldValue <= 0) {
                    scope.selectedIndex = 0;
                }
            });

            element.bind('keydown', function(e) {
                if (e.keyCode == 38) {  // Up Arrow
                    if (scope.selectedIndex == 0) {
                        return;
                    }
                    scope.selectedIndex--;
                    e.preventDefault();
                } else if (e.keyCode == 40) {  // Down Arrow
                    if (scope.selectedIndex == scope.collection.length - 1) {
                        return;
                    }
                    scope.selectedIndex++;
                    e.preventDefault();
                } else if (e.keyCode == 13) {  // Enter
                    if (scope.selectedIndex >= 0) {
                        scope.collection[scope.selectedIndex].wasHit = true;
                        scope.onEnter({row: scope.collection[scope.selectedIndex]});
                    }
                    e.preventDefault();
                }

                scope.$apply();
            });
        }
    };
}

function cdArrowRow($timeout) {
    return {
        restrict: 'A',
        scope: {
            row: '=cdArrowRow',
            selectedIndex: '=selectedIndex',
            rowIndex: '=rowIndex',
            selectedClass: '=selectedClass',
            enterClass: '=enterClass',
            enterDuration: '=enterDuration'  // milliseconds
        },
        link: function(scope, element, attrs, ctr) {
            // Apply provided CSS class to row for provided duration
            scope.$watch('row.wasHit', function(newValue) {
                if (newValue === true) {
                    element.addClass(scope.enterClass);
                    $timeout(function() { scope.row.wasHit = false;}, scope.enterDuration);
                } else {
                    element.removeClass(scope.enterClass);
                }
            });

            // Apply/remove provided CSS class to the row if it is the selected row.
            scope.$watch('selectedIndex', function(newValue, oldValue) {
                if (newValue === scope.rowIndex) {
                    element.addClass(scope.selectedClass);
                } else if (oldValue === scope.rowIndex) {
                    element.removeClass(scope.selectedClass);
                }
            });

            // Handles applying/removing selected CSS class when the collection data is filtered.
            scope.$watch('rowIndex', function(newValue, oldValue) {
                if (newValue === scope.selectedIndex) {
                    element.addClass(scope.selectedClass);
                } else if (oldValue === scope.selectedIndex) {
                    element.removeClass(scope.selectedClass);
                }
            });
        }
    }
}

该指令不仅允许您使用箭头键导航表,还允许您将回调方法绑定到Enter键。因此,当按下回车键时,当前选择的行将作为参数包含在使用该指令注册的回调方法中(onEnter)。

作为一个额外的奖励你也可以将CSS类和持续时间传递给cdArrowRow指令,这样当在所选行上点击回车键时,传入的CSS类将应用于行元素然后被删除传入持续时间后(以毫秒为单位)。这基本上允许你做一些事情,比如在输入键被击中时使行闪烁不同颜色。

查看用法:

<table cd-arrow-table="displayedCollection"
       selected-index="selectedIndex"
       on-enter="addToDB(row)">
    <thead>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="row in displayedCollection" 
            cd-arrow-row="row" 
            selected-index="selectedIndex" 
            row-index="$index" 
            selected-class="'mySelcetedClass'" 
            enter-class="'myEnterClass'" 
            enter-duration="150"
        >
            <td>{{row.firstName}}</td>
            <td>{{row.lastName}}</td>
        </tr>
    </tbody>
</table>

控制器:

angular
    .module('myApp')
    .controller('MyController', myController);

    function myController($scope) {
        $scope.selectedIndex = 0;
        $scope.displayedCollection = [
            {firstName:"John", lastName: "Smith"},
            {firstName:"Jane", lastName: "Doe"}
        ];
        $scope.addToDB;

        function addToDB(item) {
            // Do stuff with the row data
        }
    }

答案 2 :(得分:2)

这是我曾经为类似问题构建的指令。 该指令侦听键盘事件并更改行选择。

此链接有关于如何构建它的完整说明。 Change row selection using arrows

这是指令

foodApp.directive('arrowSelector',['$document',function($document){
return{
    restrict:'A',
    link:function(scope,elem,attrs,ctrl){
        var elemFocus = false;             
        elem.on('mouseenter',function(){
            elemFocus = true;
        });
        elem.on('mouseleave',function(){
            elemFocus = false;
        });
        $document.bind('keydown',function(e){
            if(elemFocus){
                if(e.keyCode == 38){
                    console.log(scope.selectedRow);
                    if(scope.selectedRow == 0){
                        return;
                    }
                    scope.selectedRow--;
                    scope.$apply();
                    e.preventDefault();
                }
                if(e.keyCode == 40){
                    if(scope.selectedRow == scope.foodItems.length - 1){
                        return;
                    }
                    scope.selectedRow++;
                    scope.$apply();
                    e.preventDefault();
                }
            }
        });
    }
};

}]);

<table class="table table-bordered" arrow-selector>....</table>

你的转发器

     <tr ng-repeat="item in foodItems" ng-class="{'selected':$index == selectedRow}">

答案 3 :(得分:1)

我有类似的要求使用箭头键支持UI导航。我最终提出的是封装在AngularJS指令中的DOM的keydown事件处理程序:

HTML:

<ul ng-controller="MainCtrl">
    <li ng-repeat="record in records">
        <div focusable tag="record" on-key="onKeyPressed" class="record">
            {{ record.name }}
        </div>
    </li>
</ul>

CSS:

.record {
    color: #000;
    background-color: #fff;
}
.record:focus {
    color: #fff;
    background-color: #000;
    outline: none;
}

JS:

module.directive('focusable', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.attr('tabindex', '-1'); // make it focusable

            var tag = attrs.tag ? scope.$eval(attrs.tag) : undefined; // get payload if defined
            var onKeyHandler = attrs.onKey ? scope.$eval(attrs.onKey) : undefined;

            element.bind('keydown', function (event) {
                var target = event.target;
                var key = event.which;

                if (isArrowKey(key)) {
                    var nextFocused = getNextElement(key); // determine next element that should get focused
                    if (nextFocused) {
                        nextFocused.focus();
                        event.preventDefault();
                        event.stopPropagation();
                    }
                }
                else if (onKeyHandler) {
                    var keyHandled = scope.$apply(function () {
                        return onKeyHandler.call(target, key, tag);
                    });

                    if (keyHandled) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                }
            });
        }
    };
});

function MainCtrl ($scope, $element) {
    $scope.onKeyPressed = function (key, record) {
        if (isSelectionKey(key)) {
            process(record);
            return true;
        }
        return false;
    };

    $element.children[0].focus(); // focus first record
}

答案 4 :(得分:1)

您可以创建一个表格导航服务,该服务跟踪当前行并公开导航方法以修改当前行的值并将焦点设置到该行。

然后,您需要做的就是创建一个键绑定指令,您可以在其中跟踪关键事件并从表导航服务中启动公开的方法,按键或按键。

我使用控制器通过名为&#39; keyDefinitions&#39;的配置对象将服务方法链接到键绑定指令。

您可以扩展keyDefinitions以包含 Enter 键(代码:13)并通过服务属性“tableNavigationService.currentRow&#39;”挂钩到所选的$ index值。或者&#39; $ scope.data&#39;,然后将其作为参数传递给您自己的自定义submit()函数。

我希望这对某人有帮助。

我已在以下plunker位置发布了此问题的解决方案:

Keyboard Navigation Service Demo

HTML:

<div key-watch>
  <table st-table="rowCollection" id="tableId" class="table table-striped">
    <thead>
      <tr>
        <th st-sort="firstName">first name</th>
        <th st-sort="lastName">last name</th>
        <th st-sort="birthDate">birth date</th>
        <th st-sort="balance" st-skip-natural="true">balance</th>
        <th>email</th>
      </tr>
    </thead>
    <tbody>
      <!-- ADD CONDITIONAL STYLING WITH ng-class TO ASSIGN THE selected CLASS TO THE ACTIVE ROW -->
      <tr ng-repeat="row in rowCollection track by $index" tabindex="{{$index + 1}}" ng-class="{'selected': activeRowIn($index)}">
        <td>{{row.firstName | uppercase}}</td>
        <td>{{row.lastName}}</td>
        <td>{{row.birthDate | date}}</td>
        <td>{{row.balance | currency}}</td>
        <td>
          <a ng-href="mailto:{{row.email}}">email</a>
        </td>
      </tr>
    </tbody>
  </table>
</div>

控制器:

  app.controller('navigationDemoController', [
    '$scope',
    'tableNavigationService',
    navigationDemoController
  ]);

  function navigationDemoController($scope, tableNavigationService) {
    $scope.data = tableNavigationService.currentRow;

    $scope.keyDefinitions = {
      'UP': navigateUp,
      'DOWN': navigateDown
    }

    $scope.rowCollection = [
      {
        firstName: 'Chris',
        lastName: 'Oliver',
        birthDate: '1980-01-01',
        balance: 100,
        email: 'chris@email.com'
      },
      {
        firstName: 'John',
        lastName: 'Smith',
        birthDate: '1976-05-25',
        balance: 100,
        email: 'chris@email.com'
      },
      {
        firstName: 'Eric',
        lastName: 'Beatson',
        birthDate: '1990-06-11',
        balance: 100,
        email: 'chris@email.com'
      },
      {
        firstName: 'Mike',
        lastName: 'Davids',
        birthDate: '1968-12-14',
        balance: 100,
        email: 'chris@email.com'
      }
    ];

    $scope.activeRowIn = function(index) {
      return index === tableNavigationService.currentRow;
    };

    function navigateUp() {
      tableNavigationService.navigateUp();
    };

    function navigateDown() {
      tableNavigationService.navigateDown();
    };

    function init() {
      tableNavigationService.setRow(0);
    };

    init();
  };
})();

服务和指令:

(function () {
  'use strict';

  var app = angular.module('tableNavigation', []);

  app.service('tableNavigationService', [
    '$document',
    tableNavigationService
  ]);
  app.directive('keyWatch', [
    '$document',
    keyWatch
  ]);

  // TABLE NAVIGATION SERVICE FOR NAVIGATING UP AND DOWN THE TABLE
  function tableNavigationService($document) {
    var service = {};

    // Your current selected row
    service.currentRow = 0;
    service.table = 'tableId';
    service.tableRows = $document[0].getElementById(service.table).getElementsByTagName('tbody')[0].getElementsByTagName('tr');

    // Exposed method for navigating up
    service.navigateUp = function () {
        if (service.currentRow) {
            var index = service.currentRow - 1;

            service.setRow(index);
        }
    };

    // Exposed method for navigating down
    service.navigateDown = function () {
        var index = service.currentRow + 1;

        if (index === service.tableRows.length) return;

        service.setRow(index);
    };

    // Expose a method for altering the current row and focus on demand
    service.setRow = function (i) {
        service.currentRow = i;
        scrollRow(i);
    }

    // Set focus to the active table row if it exists
    function scrollRow(index) {
        if (service.tableRows[index]) {
            service.tableRows[index].focus();
        }
    };

    return service;
  };

  // KEY WATCH DIRECTIVE TO MONITOR KEY DOWN EVENTS
  function keyWatch($document) {
    return {
      restrict: 'A',
      link: function(scope) {
        $document.unbind('keydown').bind('keydown', function(event) {
          var keyDefinitions = scope.keyDefinitions;
          var key = '';

          var keys = {
              UP: 38,
              DOWN: 40,
          };

          if (event && keyDefinitions) {

            for (var k in keys) {
              if (keys.hasOwnProperty(k) && keys[k] === event.keyCode) {
                  key = k;
              }
            }

            if (!key) return;

            var navigationFunction = keyDefinitions[key];

            if (!navigationFunction) {
              console.log('Undefined key: ' + key);
              return;
            }

              event.preventDefault();
                scope.$apply(navigationFunction());
                return;
          }
          return;
        });
      }
    }
  }
})();