简体   繁体   中英

Change input field in angularJS

I'm new to angularJS and want to rewrite an input field when the user presses a certain character. For example, if the user enters "aab", when the "b" is pressed I want to replace the entire field with just "y".

Using ng-keypress partly works, but leaves "yb" instead of just "y". The full example code is below. To test it enter "aab".

<html ng-app="testApp">
<body ng-controller="testCtrl as ctrl">

<form name="testForm">
<input
  type="text"
  ng-keypress="ctrl.keyPressFunc($event)"
  name="testName"
  ng-model="ctrl.testValue"
  required
>
<br/>
ctrl.testValue: {{ctrl.testValue}} <br/>
ctrl.eventa: {{ctrl.eventa}} <br/>
<p/>
ctrl.eventa.charCode: {{ctrl.eventa.charCode}} <br/>
ctrl.eventa.keyCode: {{ctrl.eventa.keyCode}} <br/>
ctrl.eventa.shiftKey: {{ctrl.eventa.shiftKey}} <br/>
ctrl.eventa.altKey: {{ctrl.eventa.altKey}} <br/>
ctrl.eventa.ctrlKey: {{ctrl.eventa.ctrlKey}} <br/>
</form>

<script
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js">
</script>

<script type="text/javascript">
  angular.module('testApp', [])
    .controller('testCtrl', [function () {
      var self = this;
      self.eventa = null;
      self.testValue = "x";       // initialize the input field

      // When the user presses 'b', change the entire testValue to "y".
      self.keyPressFunc = function(eventa) {
        self.eventa = eventa;
        if (eventa.charCode == 98) {   // if 'b'
          self.testValue = "y";
        }
      };

    }]);
</script>
</body>
</html>

How can I get angularJS to show "y" and not "yb"? Many thanks!

Use preventDefault when 'b' was pressed.

self.keyPressFunc = function(eventa) {
    self.eventa = eventa;
    if (eventa.charCode == 98) {   // if 'b'
      self.testValue = "y";
      eventa.preventDefault();
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM