解决ng-repeat产生的ng-model中取不到值的问题
2018-10-02 14:01
716 查看
最近遇到在ng-repeat产生的textarea中绑定ng-model后,在js中取不到ng-model值的问题。
html的代码结构如下
<div class="ques-item hide1 show9a" id="q10"> <div class="ques-item-question"> 10.{{questions[9].questionContent}} </div> <div class="ques-item-option"> <div ng-repeat="option in questions[9].options"> <input type="{{questions[9].questionType}}" name="problem10" value="{{option.optionCode}}" id="{{option.id}}"> <label for="{{option.id}}">{{option.optionContent}}</label> <textarea ng-if="$index == 4" class="ques-option-text" name="" id="" cols="30" rows="1" ng-model="text10"></textarea> </div> </div> </div>
用ng-repeat循环输出了该题目的选项,有的选项后面有输入框,于是用ng-if控制某个选项后面添加textarea输入框。在用ng-model双向绑定了text10后,当输入框中输入内容时,js中的$scope.text10并不能取得内容。
经过查询发现原因是,ng-repeat会产生子作用域,而js中的scope是父作用域的,Angularjs中的作用域向上查找,所以是不能取得ng-repeat中的绑定值的。
解决方案就是把子scope中的值通过$parent属性传递给父scope,同时把text10定义为数组,即前端绑定时使用$parent.text10[$index],这样就绑定了每一个textarea输入框的值,从而能在js中获取到。
修改后如下:
<div class="ques-item hide1 show9a" id="q10"> <div class="ques-item-question"> 10.{{questions[9].questionContent}} </div> <div class="ques-item-option"> <div ng-repeat="option in questions[9].options"> <input type="{{questions[9].questionType}}" name="problem10" value="{{option.optionCode}}" id="{{option.id}}"> <label for="{{option.id}}">{{option.optionContent}}</label> <textarea ng-if="$index == 4" class="ques-option-text" name="" id="" cols="30" rows="1" ng-model="$parent.text10[4]"></textarea> </div> </div> </div>
以上这篇解决ng-repeat产生的ng-model中取不到值的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- ng-repeat产生的ng-model中取不到值的问题
- angularjs select标签使用ng-repeat标签之后,ng-model无法更新问题解决
- angularjs WdatePicker ng-model问题解决
- 【AngularJS】解决ng-if中的ng-model值无效的问题
- 解决angularjs 使用 ng-repeat 循环输出时html元素无法解析的问题
- angularjs在ng-repeat中使用ng-model遇到的问题
- 【AngularJS】解决ng-if中的ng-model值无效的问题
- ng-bind-html在ng-repeat中问题的解决办法
- 【Angularjs】ng-repeat中使用ng-model遇到的问题
- ng-repeat遍历空数组或无键名的数组问题的解决
- [Angularjs]ng-repeat中使用ng-model遇到的问题
- 解决angular2在双向数据绑定时[(ngModel)]无法使用的问题
- ng-bind-html在ng-repeat中问题的解决办法
- angularjs在ng-repeat中使用ng-model遇到的问题
- AngularJS解决ng-if中的ng-model值无效的问题
- angularJs中ng-repeat遍历动态生成的表单元素绑定ng-model无效的问题
- AngularJS ng-repeat指令中使用track by子语句解决重复数据遍历错误问题
- 【AngularJS】解决ng-if中的ng-model值无效的问题(转)
- 解决angular双向绑定无效果,ng-model不能正常显示的问题
- 解决angularjs WdatePicker ng-model的问题