在angularjs中使用列表中的键盘快捷键

  
  • {{StoreList.StoreName}}
No Result Found
var angular = angular.module('mvcapp', []); angular.controller('AngularController', function ($scope, $http) { $scope.obj = {}; $scope.obj.showList = false; Getallitem() function Getallitem() { $http.get('/Coupons/GetStore').success(function (data) { $scope.Store = data; }); } $scope.SelectedValue = function (item) { $scope.sname = item; $scope.obj.showList = false; } });

}

这是我在Angularjs中过滤列表的代码。 这段代码一切都很好。 我真正想要的是在箭头键列表中使用键盘并使用enter选择值。 所以当过滤列表时我也可以使用键盘。

你可以这样做(如果你不想使用任何库):

 angular.module('app', []) .controller('Controller', function($scope,$filter) { $scope.obj = {}; $scope.obj.showList = false; $scope.Getallitem = function() { $scope.Store =[ 'Flipkart', 'Amazon', 'Snapdeal', 'Jabong', 'Trendin', 'Lenskart', 'Zovi', 'BabyOye', 'ShopMore24', 'BasicsLife', 'PrettySecrets', 'American Swan', 'ShopClues', 'FernsNPetals', 'Pepperfry', 'Koovs', 'FoodPanda', 'BookmyFlower', 'Printvenue', 'Amar Chitra Katha'] ; } $scope.Getallitem(); $scope.SelectedValue = function(item) { $scope.obj.showList = false; $scope.obj.sname = item; } $scope.open = function(index) { var filteredContent = $filter('filter')($scope.Store,$scope.obj.sname); if(typeof filteredContent[index] !== 'undefined'){ var StoreName = filteredContent[index]; $scope.SelectedValue(StoreName); } } $scope.focusIndex = -1; $scope.keys = []; $scope.keys.push({ code: 13, action: function() { $scope.open($scope.focusIndex); } }); $scope.keys.push({ code: 38, action: function() { $scope.focusIndex--; } }); $scope.keys.push({ code: 40, action: function() { $scope.focusIndex++; } }); $scope.$watch('obj.sname', function() { if(!$scope.obj.showList){ $scope.focusIndex = -1; } }); $scope.$on('keydown', function(msg, obj) { var code = obj.code; if(code != 40 && code != 38 && code != 13){ $scope.obj.showList = true; } var filteredContent = $filter('filter')($scope.Store,$scope.obj.sname); $scope.keys.forEach(function(o) { if (o.code !== code) { return; } if(code == 40){ if (($scope.focusIndex + 1) >= filteredContent.length) { return; } }else if(code == 38){ if ($scope.focusIndex <= 0) { return; } } o.action(); $scope.$apply(); }); }); }) .directive('keyTrap', function() { return function(scope, elem) { elem.bind('keydown', function(event) { if(event.keyCode == 40 || event.keyCode == 38 || event.keyCode == 13){ event.preventDefault(); } scope.$broadcast('keydown', { code: event.keyCode }); }); }; }); 
 /* Styles go here */ li.record { height: 25px; background-color: lightgray; margin: 10px; padding: 10px; width: 200px; } li.record-highlight { height: 50px; background-color: green; margin: 10px; padding: 10px; width: 200px; color: #fff; } 
       
  • {{StoreList}}
No Result Found