javascript 角度js中textArea的2路绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24079505/
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
2-way binding of textArea in angular js
提问by Aks
I have a list of question that user has to answer.For that a have prepared a form.
我有一个用户必须回答的问题列表。为此,我准备了一个表格。
The html form is
html表单是
<div class="list" ng-repeat="question in questions.data.Question" >
<div class="item item-divider">
{{question.text}}
</div>
<label class="item item-input" ng-if="question.type =='comment'">
<textarea placeholder="Comments"></textarea>
</label>
</div>
now my json string is
现在我的 json 字符串是
{
"sucess": true,
"message": "record(s) fetched sucessfully",
"data": {
"Question": [
{
"id": "4",
"text": "how was it?",
"type": "comment"
},
{
"id": "6",
"text": "how was it?",
"type": "comment"
}
]
}
}
now when user submit the form I should get the comment user has posted of all the question.
现在,当用户提交表单时,我应该得到用户发布的所有问题的评论。
回答by holgac
I am not angular expert, but I think you need to add ng-model to the textarea element.
我不是角度专家,但我认为您需要将 ng-model 添加到 textarea 元素。
<div class="list" ng-repeat="question in questions.data.Question" >
<div class="item item-divider">
{{question.text}}
</div>
<label class="item item-input" ng-if="question.type =='comment'">
<textarea placeholder="Comments" ng-model="question.comments"></textarea>
</label>
</div>
And, you also need to add 'comments' field to each comment type question. Example:
而且,您还需要为每个评论类型的问题添加“评论”字段。例子:
{
"id": "6",
"text": "how was it?",
"type": "comment",
"comments": ""
}
Note that you may not need to add "comments" field if there is a 'force add field' flag for angularjs that i'm not aware of.
请注意,如果 angularjs 有一个我不知道的“强制添加字段”标志,则您可能不需要添加“评论”字段。
回答by Satish
You have to bind ng-model to the textarea, it works even if you don't have the "answer" variable in your initial json data. I have added a button for demo purpose. Full example on JSFIDDLE
您必须将 ng-model 绑定到 textarea,即使您的初始 json 数据中没有“answer”变量,它也可以工作。我添加了一个用于演示目的的按钮。JSFIDDLE 上的完整示例
<div id="qApp" ng-controller="qAppCntrl">
<div class="list" ng-repeat="question in questions.data.Question track by $index" >
<div class="item item-divider">
{{question.text}}
</div>
<label class="item item-input" ng-if="question.type =='comment'">
<textarea placeholder="Comments" ng-model="question.answer"></textarea>
</label>
</div>
<button ng-click="submit()">Post</button>
</div>