Can I make it easier to hit enter with AngularJS?

I already have this code that I came up with:

In my external controller:

$scope.key = function ($event) { $scope.$broadcast('key', $event.keyCode) } 

In my internal controller (I have more than one such)

  $scope.$on('key', function (e, key) { if (key == 13) { if (ts.test.current) { var btn = null; if (ts.test.userTestId) { btn = document.getElementById('viewQuestions'); } else { btn = document.getElementById('acquireTest'); } $timeout(function () { btn.focus(); btn.click(); window.setTimeout(function () { btn.blur(); }, 500); }) } } }); 

Is there any other way that I could simplify using some AngularJS functions that I haven't included here?

+6
source share
2 answers

Please check this method, https://gist.github.com/EpokK/5884263

You can simply create the ng-enter directive and pass your action as a paramater

 app.directive('ngEnter', function() { return function(scope, element, attrs) { element.bind("keydown keypress", function(event) { if(event.which === 13) { scope.$apply(function(){ scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; }); 

HTML

 <input ng-enter="myControllerFunction()" /> 

You can change the name ng-enter to something else, because ng-** reserved by the main Angular command.

I also see that your controller is dealing with the DOM, and you shouldn't. Move this logic to another directive or to HTML, and keep the controller worse.

 if (ts.test.userTestId) { btn = document.getElementById('viewQuestions'); //NOT in controller } else { btn = document.getElementById('acquireTest'); //NOT in controller } $timeout(function () { btn.focus(); //NOT in controller btn.click(); //NOT in controller window.setTimeout(function () { // $timeout in $timeout, questionable btn.blur(); //NOT in controller }, 500); }) 
+6
source

What I did in the past is a directive that simply listens to the input data of the key input, and then performs the function provided to it like an ng-click. This forces the logic to remain in the controller and allows multiple elements to be reused.

 //directive angular.module('yourModule').directive('enterHandler', [function () { return{ restrict:'A', link: function (scope, element, attrs) { element.bind("keydown keypress", function (event) { var key = event.which ? event.which : event.keyCode; if (key === 13) { scope.$apply(function () { scope.$eval(attrs.enterHandler); }); event.preventDefault(); } }); } } }]); 

then your controller will become

  $scope.eventHandler = function(){ if (ts.test.current) { var btn = ts.test.userTestId ? document.getElementById('viewQuestions') : document.getElementById('acquireTest'); $timeout(function () { btn.focus(); btn.click(); window.setTimeout(function () { btn.blur(); }, 500); }) } } 

and your markup may be

 <div enter-handler="eventHandler()" ></div> 
+2
source

All Articles