按键时触发AngularJS $范围事件

时间:2015-05-20 13:05:22

标签: javascript html angularjs angularjs-scope

是否可以在按键上触发$scope function。我想知道在“表格案例”中处理按键的最舒适方式。我创建了一个虚拟plunker

控制器

// Code goes here
var myApp = angular.module("myApp", []);

//main controller define
myApp.controller('MainCtrl', ['$scope', MainCtrl]);

/**
 * MainCtrl object wrapper
 */
function MainCtrl ($scope) {

  /**
   * Submit function
   */
  $scope.submit = function () {
    console.log('Submit was triggered');
  }
}

视图

<!DOCTYPE html>
<html>
  <head>
    <script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="MainCtrl">
      <input type="text" placeholder="Trigger on enter key" />
      <button ng-click="submit();">Trigger on click</button>
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

尝试将其打包在form标记中并使用ng-submit

<form ng-submit="submit()">
    <input type="text" placeholder="Trigger on enter key" />
    <button>Trigger on click</button>
</form>