Javascript 如何使用 AngularJs 从文本框中检索值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31849643/
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 to retrieve the value from textbox using AngularJs?
提问by Naga Bhavani
$scope.add=function()
{
//How to retrieve the value of textbox
}
<input type='text'><button ng-click='add()'></button>
When I click on the button, how can I retrieve the textbox value in the controller and add that value to the table dynamically?
当我单击按钮时,如何检索控制器中的文本框值并将该值动态添加到表中?
回答by Pankaj Parkar
Assign ng-model
to it so that variable will be available inside scope
of controller.
分配ng-model
给它,以便变量在scope
控制器内部可用。
Markup
标记
<input type='text' ng-model="myVar"/>
<button type="button" ng-click='add(myVar)'></button>
回答by JimL
Bind the text field using ng-model
使用ng-model绑定文本字段
Example:
例子:
$scope.items = [];
$scope.newItem = {
title: ''
}
$scope.add = function(item) {
$scope.items.push(item);
$scope.newItem = { title: '' }; // set newItem to a new object to lose the reference
}
<input type='text' ng-model='newItem.title'><button ng-click='add(newItem)'>Add</button>
<ul>
<li ng-repeat='item in items'>{{ item.title }}</li>
</ul>
回答by keyvan salimi
To take your data from textbox
, you should use ng-model
attribute on the HTML element. On the button
element you can use ng-click
with a parameter which is your ng-model
要从 中获取数据textbox
,您应该ng-model
在 HTML 元素上使用属性。在button
元素上,您可以使用ng-click
一个参数ng-model
Example: Your HTML:
示例:您的 HTML:
<input type='text' ng-model="YourTextData"/>
<button type="button" ng-click='add(YourTextData)'></button>
Your Js:
你的JS:
$scope.add=function(YourTextData){
//Put a debugger in here then check the argument
}
回答by Bidhan
Use ng-model in your textbox to bind them to your scope variables
在文本框中使用 ng-model 将它们绑定到作用域变量
<input type="text" ng-model="value1">
<input type="text" ng-model="value2">
Then declare the variables inside your controller and use them in your function
然后在控制器中声明变量并在函数中使用它们
$scope.value1 = 0;
$scope.value2 = 0;
$scope.add=function()
{
// Example
console.log($scope.value1 + $scope.value2);
}