如何创建一个表格,我可以使用箭头使用Angular导航数据?

时间:2016-04-06 19:37:48

标签: angularjs

我正在寻找基于Angular.JS的方法来创建一个“数据值表,当用户按左/右箭头键时值会发生变化”。

这个想法是提供一个屏幕目录,用户将向左/右页面查看页面。

我是Angular的新手,并希望能够正确使用它。

我现在拥有的是基于jQuery的方法。我可以获得一个好主意,示例或指导我如何在Angular中执行此操作的教程吗?

见下面的例子。

//assume that the data comes from external source and its structure cannot be changed
//well it can, but point is that the format is {index => object, index => object, ... }
data = {
  "0": "zero",
  "1": "one",
  "2": "two",
  "3": "three",
  "4": "four",
  "5": "five",
}


counter = 0;

//arrow functionality
$(document).keydown(function(e) {
  switch (e.which) {
    case 37: // left
      counter--;
      if (counter < 0) counter = 5;
      $('#data').text(data[counter]);

      break;


    case 39: // right
      counter++;
      if (counter > 5) counter = 0;
      $('#data').text(data[counter]);
      break;

    default:
      return;
  }
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<table border="1">
  <tr>

    <td style="font-size:2em">My value is =></td>
    <td id="data" style="font-size:4em"><strong>zero</strong>
    </td>
  </tr>
  <tr>

    <td colspan="2">Use left/right arrows on your keyboard to change value above<br>
    You may have to first click inside the example area.</td>
  </tr>

</table>

1 个答案:

答案 0 :(得分:2)

一种方法是:

app.js:

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

app.controller('indexCtrl', indexCtrl);
indexCtrl.$inject = ['$scope', '$window'];
function indexCtrl($scope, $window) {

  $scope.data = {
    "0": "zero",
    "1": "one",
    "2": "two",
    "3": "three",
    "4": "four",
    "5": "five",
  };
  $scope.counter = 0;

  angular.element($window).bind('keydown', function(e) {
    if (e.which == 37) {
      $scope.counter--;
      if ($scope.counter < 0) $scope.counter = 5;
    } else if (e.which == 39) {
      $scope.counter++;
      if ($scope.counter > 5) $scope.counter = 0;
    }
    $scope.$apply();
  });
}

<强>的index.html:

<!DOCTYPE html>
<html ng-app="myApp">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="indexCtrl">
    <table border="1">
  <tr>
    <td style="font-size:2em">My value is =></td>
    <td style="font-size:4em"><strong>{{data[counter]}}</strong>
    </td>
  </tr>
  <tr>

    <td colspan="2">Use left/right arrows on your keyboard to change value above<br>
    You may have to first click inside the example area.</td>
  </tr>

</table>
  </body>
</html>
相关问题