解決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后,當(dāng)輸入框中輸入內(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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Angular中實(shí)現(xiàn)樹形結(jié)構(gòu)視圖實(shí)例代碼
近兩年當(dāng)中使用Angular開發(fā)過很多項目,其中也涉及到一些樹形結(jié)構(gòu)視圖的顯示,最近的在項目中封裝了大量的組件,一些組件也有樹形結(jié)構(gòu)的展示,所以寫出來總結(jié)一下。2017-05-05
詳解Angular-ui-BootStrap組件的解釋以及使用
這篇文章主要介紹了詳解Angular-ui-BootStrap組件的解釋以及使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
angular4 如何在全局設(shè)置路由跳轉(zhuǎn)動畫的方法
本篇文章主要介紹了angular4 如何在全局設(shè)置路由跳轉(zhuǎn)動畫的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08
詳解AngularJS通過ocLazyLoad實(shí)現(xiàn)動態(tài)(懶)加載模塊和依賴
本篇文章主要介紹了詳解AngularJS通過ocLazyLoad實(shí)現(xiàn)動態(tài)(懶)加載模塊和依賴 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03
Angularjs中如何使用filterFilter函數(shù)過濾
這篇文章主要介紹了Angularjs中如何使用filterFilter函數(shù)過濾的相關(guān)資料,需要的朋友可以參考下2016-02-02

