var app = angular.module('plunker', []);
app.directive('arrowListener', function() {
return {
restrict: 'A', // attribute
scope: {
moveRight: '&', // bind to parent method
moveLeft: '&'
},
link: function(scope, elm, attrs) {
elm.bind('keydown', function(e) {
if (e.keyCode === 39) {
scope.moveRight();
}
if (e.keyCode === 37) {
scope.moveLeft();
}
});
}
};
}).controller('MainCtrl', function($scope) {
var history = [];
$scope.numbersDisplayed = [0, 1, 2, 3, 4, 5];
$scope.moveRight = function() {
history.unshift($scope.numbersDisplayed.shift());
$scope.$apply();
};
$scope.moveLeft = function() {
$scope.numbersDisplayed.unshift(history.shift());
$scope.$apply();
};
});
<!DOCTYPE html>
<html ng-app="plunker" ng-controller="MainCtrl" >
<head>
<title></title>
<script src="http://code.angularjs.org/1.2.1/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
</head>
<body arrow-listener move-left="moveLeft()" move-right="moveRight()">
<p ng-repeat="num in numbersDisplayed">{{ num }}</p>
</body>
</html>
/* CSS goes here */