6

I want to fire a button's click event when pressing ENTER inside a input and I find it quite difficult with AngularJS.

My view (simplified, updated):

<!doctype html>
<html lang="en" ng:app="test">
    <head>
        <meta charset="utf-8" />
        <title>Test</title>
        <link rel="stylesheet" href="css/app.css" />
    </head>
    <body ng-controller="TestController">
        <button ng-click="onButton1Click()" class="btn1">Click Me</button>
        <button ng-click="onButton2Click()" class="btn2">Don't click me</button>
        <script src="lib/jquery/jquery.js"></script>
        <script src="lib/angular/angular.js"></script>
        <script src="js/testcontroller.js"></script>
    </body>
</html>

My controller for this view:

'use strict';

angular.module('test', [])
.controller('TestController', ['$scope',
    function($scope) {

        $scope.onButton1Click = function() {
            alert("Hello");
        }

        $scope.onButton2Click = function() {
            $('.btn2').click();
        }
}])

I simplified all the code to this. When I click on btn2 I get this error

$apply already in progress

No, I can't call $scope.onButton1Click() directly, I must simulate the btn1 click.

ali
  • 10,927
  • 20
  • 89
  • 138

3 Answers3

13

You mentioned

fire a button's click event when pressing ENTER inside a input

So if it is safe to assume that you can have a form I would prefer using ng-submit as shown below.

<form ng-submit="clickEventFunction()">
  <input type="text"/>
  <button type="submit">Click</button>
</form>

Note button type should be submit.

skeep
  • 940
  • 6
  • 14
3

This took me a while to figure out (lots of fiddles).

<form id="nowsorting" ng-submit="getData(sc_user)">Now sorting the Soundcloud likes of <input type="text" ng-model="sc_user"><input type="submit" value="Sort"></form>

Make a form and use ng-submit to fire the event (likely a function).

Then create two inputs (one is "text" and the other "submit").

Then pushing enter should fire the ng-submit event/function.

Kyle Pennell
  • 5,747
  • 4
  • 52
  • 75
1

I think, you just have to call your $scope.onButtonClick()

Please check this Plunker

$scope.onKeyPress = function($event) {
   if ($event.keyCode == 13) {
      $scope.onButtonClick();
   }
};
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
bfcamara
  • 323
  • 1
  • 2
  • 10
  • 1
    This doesn't really 'click' the button it just executes the same javascript code that is wired to the click of the button. it's slightly different since any additional listeners you have on that button click won't be triggered. – Randyaa May 13 '15 at 17:32