Issue
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
Solution
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">
Answered By – dfsq
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0