如何在AngularJS中使用按键事件?

本文翻译自:How to use a keypress event in AngularJS?

I want to catch the enter key press event on the textbox below. 我想在下面的文本框中捕获回车键按下事件。 To make it more clear I am using a ng-repeat to populate the tbody. 为了更清楚,我使用ng-repeat来填充tbody。 Here is the HTML: 这是HTML:

<td><input type="number" id="closeqty{{$index}}" class="pagination-right closefield" 
    data-ng-model="closeqtymodel" data-ng-change="change($index)" required placeholder="{{item.closeMeasure}}" /></td>

This is my module: 这是我的模块:

angular.module('components', ['ngResource']);

I am using a resource to populate the table and my controller code is: 我正在使用资源填充表,我的控制器代码是:

function Ajaxy($scope, $resource) {
//controller which has resource to populate the table 
}

#1楼

参考:https://stackoom.com/question/1BIww/如何在AngularJS中使用按键事件


#2楼

You need to add a directive , like this: 你需要添加一个directive ,如下所示:

Javascript : Javascript

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();
            }
        });
    };
});

HTML : HTML

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" my-enter="doSomething()">    
</div>

#3楼

An alternative is to use standard directive ng-keypress="myFunct($event)" 另一种方法是使用标准指令ng-keypress="myFunct($event)"

Then in your controller you can have: 然后在您的控制器中,您可以:

...

$scope.myFunct = function(keyEvent) {
  if (keyEvent.which === 13)
    alert('I am an alert');
}

...

#4楼

Some example of code that I did for my project. 我为我的项目做的一些代码示例。 Basically you add tags to your entity. 基本上,您可以向实体添加标签。 Imagine you have input text, on entering Tag name you get drop-down menu with preloaded tags to choose from, you navigate with arrows and select with Enter: 想象一下,您有输入文本,在输入标记名称时,您将获得带有预加载标记的下拉菜单,您可以使用箭头导航并使用回车选择:

HTML + AngularJS v1.2.0-rc.3 HTML + AngularJS v1.2.0-rc.3

    <div>
        <form ng-submit="addTag(newTag)">
            <input id="newTag" ng-model="newTag" type="text" class="form-control" placeholder="Enter new tag"
                   style="padding-left: 10px; width: 700px; height: 33px; margin-top: 10px; margin-bottom: 3px;" autofocus
                   data-toggle="dropdown"
                   ng-change="preloadTags()"
                   ng-keydown="navigateTags($event)">
            <div ng-show="preloadedTags.length > 0">
                <nav class="dropdown">
                    <div class="dropdown-menu preloadedTagPanel">
                        <div ng-repeat="preloadedTag in preloadedTags"
                             class="preloadedTagItemPanel"
                             ng-class="preloadedTag.activeTag ? 'preloadedTagItemPanelActive' : '' "
                             ng-click="selectTag(preloadedTag)"
                             tabindex="{{ $index }}">
                            <a class="preloadedTagItem"
                               ng-class="preloadedTag.activeTag ? 'preloadedTagItemActive' : '' "
                               ng-click="selectTag(preloadedTag)">{{ preloadedTag.label }}</a>
                        </div>
                    </div>
                </nav>
            </div>
        </form>
    </div>

Controller.js Controller.js

$scope.preloadTags = function () {
    var newTag = $scope.newTag;
    if (newTag && newTag.trim()) {
        newTag = newTag.trim().toLowerCase();

        $http(
            {
                method: 'GET',
                url: 'api/tag/gettags',
                dataType: 'json',
                contentType: 'application/json',
                mimeType: 'application/json',
                params: {'term': newTag}
            }
        )
            .success(function (result) {
                $scope.preloadedTags = result;
                $scope.preloadedTagsIndex = -1;
            }
        )
            .error(function (data, status, headers, config) {
            }
        );
    } else {
        $scope.preloadedTags = {};
        $scope.preloadedTagsIndex = -1;
    }
};

function checkIndex(index) {
    if (index > $scope.preloadedTags.length - 1) {
        return 0;
    }
    if (index < 0) {
        return $scope.preloadedTags.length - 1;
    }
    return index;
}

function removeAllActiveTags() {
    for (var x = 0; x < $scope.preloadedTags.length; x++) {
        if ($scope.preloadedTags[x].activeTag) {
            $scope.preloadedTags[x].activeTag = false;
        }
    }
}

$scope.navigateTags = function ($event) {
    if (!$scope.newTag || $scope.preloadedTags.length == 0) {
        return;
    }
    if ($event.keyCode == 40) {  // down
        removeAllActiveTags();
        $scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex + 1);
        $scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
    } else if ($event.keyCode == 38) {  // up
        removeAllActiveTags();
        $scope.preloadedTagsIndex = checkIndex($scope.preloadedTagsIndex - 1);
        $scope.preloadedTags[$scope.preloadedTagsIndex].activeTag = true;
    } else if ($event.keyCode == 13) {  // enter
        removeAllActiveTags();
        $scope.selectTag($scope.preloadedTags[$scope.preloadedTagsIndex]);
    }
};

$scope.selectTag = function (preloadedTag) {
    $scope.addTag(preloadedTag.label);
};

CSS + Bootstrap v2.3.2 CSS + Bootstrap v2.3.2

.preloadedTagPanel {
    background-color: #FFFFFF;
    display: block;
    min-width: 250px;
    max-width: 700px;
    border: 1px solid #666666;
    padding-top: 0;
    border-radius: 0;
}

.preloadedTagItemPanel {
    background-color: #FFFFFF;
    border-bottom: 1px solid #666666;
    cursor: pointer;
}

.preloadedTagItemPanel:hover {
    background-color: #666666;
}

.preloadedTagItemPanelActive {
    background-color: #666666;
}

.preloadedTagItem {
    display: inline-block;
    text-decoration: none;
    margin-left: 5px;
    margin-right: 5px;
    padding-top: 5px;
    padding-bottom: 5px;
    padding-left: 20px;
    padding-right: 10px;
    color: #666666 !important;
    font-size: 11px;
}

.preloadedTagItem:hover {
    background-color: #666666;
}

.preloadedTagItemActive {
    background-color: #666666;
    color: #FFFFFF !important;
}

.dropdown .preloadedTagItemPanel:last-child {
    border-bottom: 0;
}

#5楼

You can also apply it to a controller on a parent element. 您还可以将其应用于父元素上的控制器。 This example can be used to highlight a row in a table by pressing up/down arrow keys. 此示例可用于通过按向上/向下箭头键突出显示表中的行。

app.controller('tableCtrl', [ '$scope', '$element', function($scope, $element) {
  $scope.index = 0; // row index
  $scope.data = []; // array of items
  $scope.keypress = function(offset) {
    console.log('keypress', offset);
    var i = $scope.index + offset;
    if (i < 0) { i = $scope.data.length - 1; }
    if (i >= $scope.data.length) { i = 0; }
  };
  $element.bind("keydown keypress", function (event) {
    console.log('keypress', event, event.which);
    if(event.which === 38) { // up
      $scope.keypress(-1);
    } else if (event.which === 40) { // down
      $scope.keypress(1);
    } else {
      return;
    }
    event.preventDefault();
  });
}]);


<table class="table table-striped" ng-controller="tableCtrl">
<thead>
    <tr>
        <th ng-repeat="(key, value) in data[0]">{{key}}</th>
    </tr>
</thead>
<tbody>
    <tr ng-repeat="row in data track by $index" ng-click="draw($index)" ng-class="$index == index ? 'info' : ''">
        <td ng-repeat="(key, value) in row">{{value}}</td>
    </tr>
</tbody>
</table>


#6楼

Another simple alternative: 另一种简单的选择

<input ng-model="edItem" type="text" 
    ng-keypress="($event.which === 13)?foo(edItem):0"/>

And the ng-ui alternative: 和ng-ui替代方案:

<input ng-model="edItem" type="text" ui-keypress="{'enter':'foo(edItem)'}"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
AngularJS使用mock数据是一种常见的做法,可以帮助我们进行前端开发和测试。下面是一个简单的示例,演示如何在AngularJS使用mock数据。 首先,你需要创建一个mock数据文件,可以是一个JSON文件或JavaScript文件,来模拟接口返回的数据。例如,创建一个名为`mockData.js`的文件,内容如下: ```javascript angular.module('myApp') .value('mockData', { users: [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Bob' } ] }); ``` 接下来,在你的AngularJS应用,你可以使用`$httpBackend`来拦截请求并返回mock数据。例如,在你的控制器注入`mockData`服务,并使用`$httpBackend`拦截请求: ```javascript angular.module('myApp') .controller('UserController', function($scope, $httpBackend, mockData) { // 拦截/users请求并返回mock数据 $httpBackend.whenGET('/users').respond(mockData.users); // 发送实际的请求 $http.get('/users').then(function(response) { $scope.users = response.data; }); }); ``` 这样,当你发送一个GET请求到`/users`时,`$httpBackend`会拦截请求并返回mock数据。 最后,确保在你的应用加载mock数据文件和设置`ngMockE2E`模块。例如: ```javascript angular.module('myApp', ['ngMockE2E']) .run(function($httpBackend) { // 启用ngMockE2E来拦截请求 $httpBackend.whenGET(/.*/).passThrough(); }); ``` 这样,AngularJS应用就配置好了使用mock数据。 注意,这只是一个简单的示例,实际的应用可能涉及更复杂的场景和数据。 希望对你有所帮助!如果你有任何进一步的问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值