[英]How I can trigger a function with a button click which is already set to be triggered with "Enter" Key press in AngularJS?
所以我試圖通過點擊 ENTER 鍵旁邊的按鈕將產品添加到購物車(這是現在將產品添加到購物車的唯一方法),我已經嘗試了很多次,但不幸的是所有方法都可以根本不工作。 這是一個用 AngularJS 構建的 POS 系統項目(我在這方面的經驗非常薄弱)而且我需要把它做得很糟糕,這里是 HTML 部分:
<tr>
<td colspan="6" class="text-center">
<input autofocus autocomplete="off" list="product-list"
id="product-entry" type="text" class="form-control"
name="product-reference" required/><br/>
<button id="myButton" ng-click="" >Add Product to Sale</button>
<datalist id="product-list">
<option ng-repeat="item in inventory" value="{{ item.name }}">
</option>
</datalist>
</td>
</tr>
我需要在有人點擊“myButton”時完成它,我想我需要在 ng-click 指令中添加一些功能,但歡迎任何其他方式
這是 JS 部分:
// POS Section
pos.controller('posController', function ($scope, $routeParams, Inventory, Transactions) {
$scope.barcode = '';
function barcodeHandler (e) {
$scope.barcodeNotFoundError = false;
$scope.barcode = $('#product-entry').val();
var regex=/^[0-9]+$/;
// if enter is pressed
if (e.which === 13) {
if(!$scope.barcode.match(regex)){
for(var i = 0; i < $scope.inventory.length; i++) {
if($scope.inventory[i].name === $scope.barcode) {
$scope.barcode = $scope.inventory[i].barcode;
break;
}
}
}
if ($scope.isValidProduct($scope.barcode)) {
$scope.addProductToCart($scope.barcode);
$scope.barcode = '';
$scope.productsList = '';
$scope.$digest();
$('#product-entry').val($scope.barcode);
}
else {
window.alert('product not found: ' + $scope.barcode);
console.log('invalid product: ' + $scope.barcode);
// $scope.barcodeNotFoundError = true;
}
}
}
$('#product-entry').off('keypress').on('keypress', barcodeHandler);
您正在做的是偵聽字段上的 keyup 事件,如果該鍵與返回鍵匹配,則繼續執行您的邏輯。
如果你將邏輯移到它自己的函數中(在barcodeHandler之前),你可以在其他地方訪問它:
$scope.doSomething = function() {
$scope.barcodeNotFoundError = false;
$scope.barcode = $('#product-entry').val();
var regex=/^[0-9]+$/;
if(!$scope.barcode.match(regex)){
for(var i = 0; i < $scope.inventory.length; i++) {
if($scope.inventory[i].name === $scope.barcode) {
$scope.barcode = $scope.inventory[i].barcode;
break;
}
}
}
if ($scope.isValidProduct($scope.barcode)) {
$scope.addProductToCart($scope.barcode);
$scope.barcode = '';
$scope.productsList = '';
$('#product-entry').val($scope.barcode);
}
else {
window.alert('product not found: ' + $scope.barcode);
console.log('invalid product: ' + $scope.barcode);
// $scope.barcodeNotFoundError = true;
}
};
然后在barcodeHandler里面,使用:
if (e.which === 13) {
$scope.doSomething();
}
現在在您的標記中,您可以執行以下操作:
<button id="myButton" ng-click="doSomething()">Add Product to Sale</button>
向控制器的$scope
添加一些東西是使其在視圖中可用的一種方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.