Reputation: 450
I want to modify my input value and separate it using dash -
<input type="text" ng-keypress="addHyphen($this)" id="sortcode" name="sortcode" maxlength="6" ng-model="data.branchTransitNumber" />
For achieving the same I wrote a ng-keypress
event and trying to modify the input.
$scope.addHyphen = function(ele) {
console.log(ele);
//var ele = document.getElementById(sortcode)
var finalVal = ele.match(/.{1,2}/g).join('-');
document.getElementById(sortcode).value = finalVal;
}
The code gives ele
as undefined
. I have even tried getting the element by idea but it also gives undefined
.
Input: 11111
While typing : 11-11-11
Upvotes: 1
Views: 759
Reputation: 29249
I'm not sure how did you get into $this
but the event handler passes only $event
Expression to evaluate upon keypress. (Event object is available as $event and can be interrogated for keyCode, altKey, etc.)
https://docs.angularjs.org/api/ng/directive/ngKeypress#ngKeypress-arguments
The right way to get the element is angular.element($event.target)
Like this:
angular
.module('app', [])
.controller('ctrl', $scope => {
$scope.addHyphen = $event => {
const $this = angular.element($event.target);
console.log($this);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" ng-keypress="addHyphen($event)" id="sortcode" name="sortcode" maxlength="6" ng-model="branchTransitNumber" />
</div>
Reference: Get the $this in angularjs
Upvotes: 1