Fire button click in AngularJS

左心房为你撑大大i 提交于 2019-12-04 22:43:36

问题


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.


回答1:


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.




回答2:


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.




回答3:


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

Please check this Plunker

$scope.onKeyPress = function($event) {
   if ($event.keyCode == 13) {
      $scope.onButtonClick();
   }
};


来源:https://stackoverflow.com/questions/16080461/fire-button-click-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!