Angular: How to get an input value using $this

10.7k views Asked by At

I am hoping to get an input value inside a keyup function that can runs from multiple inputs. Every time there is a keyup the function will trigger according to the specific input. So, I am trying to use $this inside the function. No succes so far.. HTML code:

<input ng-keyup="getRxcui()" placeholder="Type med a" id="medicineA" />
<input ng-keyup="getRxcui()" placeholder="Type med b" id="medicineB" />

Angular code:

var rxConflicts = angular.module('rxConflicts', []);

rxConflicts.controller('MainController', function($scope, $http){
    $scope.getRxcui = function(event){

        // getting the value for each medicine input
        var medValue = $(this).value;
        console.log(medValue);

    }
});

I am pretty sure $(this) is the right way to do this so that I don't need to duplicate that function for each input and use ng-model... You can take my word that the angular works fine. Any help is appreciated. Thanks

2

There are 2 answers

0
user3227295 On BEST ANSWER

use ng-model and pass it in function:

<input ng-keyup="getRxcui(medicineA)" ng-model="medicineA" placeholder="Type med a" id="medicineA" />
<input ng-keyup="getRxcui(medicineB)" ng-model="medicineB" placeholder="Type med b" id="medicineB" />

Angular code:

var rxConflicts = angular.module('rxConflicts', []);

rxConflicts.controller('MainController', function($scope, $http){
    $scope.getRxcui = function(value){

        // getting the value for each medicine input
        var medValue = value;
        console.log(medValue);

    }
});
0
adutra On

Angular 2 and superior:

You could pass the $event on the keyUp and use it to get the target (the input) and it's value. In case you're using formControls and not binding directly through ngModel

Template HTML:

<input (keyup)="getRxcui($event)">

Component.ts

getRxcui(event){

   var inputValue = event.target.value;
   console.log(inputValue);

}