Javascript 如何使用 angular.element('#id') 获取输入元素的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29684049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the value of an input element using angular.element('#id')
提问by Seshu
When I'm trying to get the value of input element using angular.element, its returning undefined. Here is my code:
当我尝试使用 angular.element 获取输入元素的值时,其返回未定义。这是我的代码:
$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
如何使用 angular.element 获取值
回答by dfsq
Explanation
解释
You should use valmethod similar to jQuery's $.fn.val:
您应该使用val类似于 jQuery 的方法$.fn.val:
console.log(angular.element('#username').val());
Alternatively you can use valueproperty of the pure HTMLInputELement:
或者,您可以使用value纯 HTMLInputELement 的属性:
console.log(angular.element('#username')[0].value);
... because angular.elementinstance is an array-like collection of HTMLElements with every element accessible by its index.
...因为angular.elementinstance 是一个类似数组的 HTMLElements 集合,每个元素都可以通过其索引访问。
Correct approach
正确的做法
But... You should never read input value like this in context of Angular app. Instead, use ngModeldirective and bind input value to angular model directly:
但是......你不应该在 Angular 应用程序的上下文中读取这样的输入值。相反,使用ngModel指令并将输入值直接绑定到角度模型:
$scope.registerUser = function() {
console.log($scope.username);
};
where in HTML you have
你在 HTML 中的位置
<input type="text" ng-model="username">
回答by Tunde Pizzle
This works for me
这对我有用
angular.element(document.getElementById('username')).val();
回答by Pankaj Shinde
You can use below options for AngularJS 2+.
您可以将以下选项用于 AngularJS 2+。
(<HTMLInputElement>document.getElementsByName("username")[0]).value(<HTMLInputElement>document.getElementsById("username")[0]).value
(<HTMLInputElement>document.getElementsByName("username")[0]).value(<HTMLInputElement>document.getElementsById("username")[0]).value
回答by Ben Jaspers
The same way as in jQuery, for which angular.elementis a wrapper/sub:
与在 jQuery 中的方式相同,它angular.element是一个包装器/子:
angular.element('#username').val();
回答by gaganKapula
In addition to the above ways, these may also be used :
除了上述方法外,还可以使用这些方法:
angular.element('[id="username"]').val();
angular.element('[id="username"]')[0].value;

