在js中如何解决ng-repeat产生的ng-model中取不到值的问题

发布时间:2021-06-26 15:20:00 作者:小新
来源:亿速云 阅读:100

小编给大家分享一下在js中如何解决ng-repeat产生的ng-model中取不到值的问题,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

最近遇到在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>

以上是“在js中如何解决ng-repeat产生的ng-model中取不到值的问题”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. ng-if ng-repeat下的ng-model赋值
  2. vue中attr取不到属性值如何解决

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js ng-repeat ng-model

上一篇:Android中怎么实现界面互调

下一篇:Android中怎么实现选项卡功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》