解決ng-repeat產(chǎn)生的ng-model中取不到值的問題
最近遇到在ng-repeat產(chǎn)生的textarea中綁定ng-model后,在js中取不到ng-model值的問題。
html的代碼結(jié)構(gòu)如下
<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循環(huán)輸出了該題目的選項,有的選項后面有輸入框,于是用ng-if控制某個選項后面添加textarea輸入框。在用ng-model雙向綁定了text10后,當輸入框中輸入內(nèi)容時,js中的$scope.text10并不能取得內(nèi)容。
經(jīng)過查詢發(fā)現(xiàn)原因是,ng-repeat會產(chǎn)生子作用域,而js中的scope是父作用域的,Angularjs中的作用域向上查找,所以是不能取得ng-repeat中的綁定值的。
解決方案就是把子scope中的值通過$parent屬性傳遞給父scope,同時把text10定義為數(shù)組,即前端綁定時使用$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產(chǎn)生的ng-model中取不到值的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Angular中使用ui router實現(xiàn)系統(tǒng)權(quán)限控制及開發(fā)遇到問題
這篇文章主要介紹了Angular中使用ui router實現(xiàn)系統(tǒng)權(quán)限控制及開發(fā)遇到問題的相關資料,本文分步驟介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2016-09-09
Angular 根據(jù) service 的狀態(tài)更新 directive
Angular JS (Angular.JS) 是一組用來開發(fā)Web頁面的框架、模板以及數(shù)據(jù)綁定和豐富UI組件。本文給大家介紹Angular 根據(jù) service 的狀態(tài)更新 directive,需要的朋友一起學習吧2016-04-04

