簡體   English   中英

僅當更改值的長度等於x時,如何在輸入文本中使用事件ng-change指令?

[英]How to use the event ng-change directive in input text only when the length of the changed value is equal to x?

我是Angular的初學者,我嘗試解決這個問題:我有一個<input/>字段:

<input 
  ng-model="codebare" 
  ng-change="addSale(codebare)" 
  name="keyWord"
  type="text" 
  class="form-control" 
  placeholder="Product name or barcode value" 
  autofocus />

正如您可能看到的那樣,我想在任何時候改變輸入值( ng-model="codebare" )。 我的問題是這個代碼只在第一個字符填充字段時工作,並且因為我使用條形碼掃描器,我想獲得完整值( 3876666667677777287 )而不是第一個字符( 3 )。 有一個簡單的方法嗎? 我認為像ng-change-options="length"這樣的指令卻無法找到它。 以下是我的addSale()函數:

$scope.addSale = function(codebare) {
    alert(codebare);
    var item = $scope.codebare;
    alert(item);
    $scope.orderedItemCnt = 1;
    var foodItem = {
        orderedItemCnt: 1,
        totalPrice: item.price,
        itemId: item.id, 
        id: $scope.itemsCnt,
        item: item
    };
}

如果您正在使用條形碼掃描儀,我會添加一個ng-model-debounce選項,因此在整個代碼有時間完全輸入之前,模型不會更新。

我在下面創建了一個示例,您可以嘗試。

 angular.module('optionsExample', []) .controller('ExampleController', ['$scope', function($scope) { var data = { 1264274554897965: { id: "AGDFT144", price: 10.50 }, 3124142142123532: { id: "AGFHH156", price: 2.15 }, 6588969543172554: { id: "BNHKL102", price: 101.60 } }; $scope.barcode = 6588969543172554; $scope.$watch("barcode", function(newValue, oldValue) { if (newValue) addSale(newValue); }); function addSale(barcode) { var item = data[barcode]; var foodItem = { orderedItemCnt: 1, totalPrice: item.price, itemId: item.id, }; console.log(foodItem); } }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <div ng-app="optionsExample" ng-controller="ExampleController"> <form name="itemForm"> <label>Name: <input type="text" name="barcode" ng-model="barcode" ng-model-options="{ debounce: 500 }" /> </label> <br /> </form> <pre>user.name = <span ng-bind="barcode"></span></pre> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM