Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the value of an input element using angular.element('#id')

When I'm trying to get the value of input element using angular.element, its returning undefined. Here is my code:

$scope.registerUser = function() {
    console.log(angular.element('#username').value); // undefined
    console.log(document.getElementById('username').value); // sampleName
};

How do I get the value using angular.element

like image 714
Seshu Vuggina Avatar asked Apr 16 '15 19:04

Seshu Vuggina


2 Answers

Explanation

You should use val method similar to jQuery's $.fn.val:

console.log(angular.element('#username').val());

Alternatively you can use value property of the pure HTMLInputELement:

console.log(angular.element('#username')[0].value);

... because angular.element instance is an array-like collection of HTMLElements with every element accessible by its index.

Correct approach

But... You should never read input value like this in context of Angular app. Instead, use ngModel directive and bind input value to angular model directly:

$scope.registerUser = function() {    
    console.log($scope.username);
};

where in HTML you have

<input type="text" ng-model="username">
like image 76
dfsq Avatar answered Sep 30 '22 00:09

dfsq


This works for me

angular.element(document.getElementById('username')).val();
like image 44
Tunde Pizzle Avatar answered Sep 30 '22 00:09

Tunde Pizzle