2-way binding of textArea in angular js

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I have a list of question that user has to answer.For that a have prepared a form.

The html form is

<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

{     "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.

回答1:

I am not angular expert, but I think you need to add ng-model to the textarea element.

<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.



回答2:

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

<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> 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!