首页 » 记事本 » 用AngularJS directive为DOM元素绑定enter事件

用AngularJS directive为DOM元素绑定enter事件

例如在表单提交的场景,用户敲击回车键实现登录操作:

<!DOCTYPE html>
<html ng-app="app">

<head>
    <title>angular</title>
    <meta charset="utf-8">
    <script src="angular.js"></script>
</head>

<body>
    <div ng-controller="test">
        <input type="text" my-enter="doSomething()">  
    </div>
    <script>
    var app = angular.module('app', []);
    app.controller('test', function($scope) {
        $scope.doSomething = function(){
            console.log("test")
        }
    });
    app.directive('myEnter', function () {
        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {
                if(event.which === 13) {
                    scope.$apply(function (){
                        scope.$eval(attrs.myEnter);
                    });

                    event.preventDefault();
                }
            });
        };
    });
    </script>
</body>

</html>
此文章发表在 记事本 标签为 . 将固定链接加入收藏.