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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值