Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  99] [ 3]  / answers: 1 / hits: 99350  / 9 Years ago, thu, april 16, 2015, 12:00:00

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


More From » jquery

 Answers
8

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>

[#67040] Wednesday, April 15, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;