AngularJS 獲取ng-repeat動(dòng)態(tài)生成的ng-model值實(shí)例詳解
AngularJS 獲取ng-repeat動(dòng)態(tài)生成的ng-model值
最近做項(xiàng)目遇到了ng-model是ng-repeat動(dòng)態(tài)生成的,ng-model=”變量”,什么變量,是未知的,所以你無法在$scope."變量"取到值,就算取到值也是其中一個(gè)值,這樣的問題,經(jīng)過百度一番查找找到解決方案,這里記錄下,也行可以幫助到大家。
代碼
html
<div> <div class="modal-header"> <h3 class="modal-title">用例集全局參數(shù)配置</h3> </div> <div class="modal-body"> <table class="table table-hover"> <thead> <tr> <th>參數(shù)</th> <th>參數(shù)值</th> </tr> </thead> <tbody ng-repeat="param in params"> <tr> <td>{{param}}</td> <td><input name="test" class="form-control" type="text" ng-trim="false" ng-model="$parent.conf[$index]"/></td> </tr> </tbody> </table> </div> <div class="modal-footer"> <button class="btn btn-primary" ng-click="ok()"> 應(yīng)用 </button> <button class="btn btn-warning" ng-click="cancel()">取消</button> </div> </div>
JS
var ModalInstanceCtrl = function ($scope, $modalInstance, params) { $scope.params = params; $scope.conf = []; $scope.ok = function () { console.log($scope.conf); $modalInstance.close($scope.conf); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; };
問題描述
因?yàn)閚g-model是ng-repeat動(dòng)態(tài)生成的,ng-model=”變量”,什么變量,是未知的,所以你無法在$scope."變量"取到值,就算取到值也是其中一個(gè)值,這個(gè)問題困擾了我一天,終于解決了。
解決方法
首先ng-model設(shè)置為$parent.conf[$index]:
- 用$parent的原因是ng-repeat產(chǎn)生的,他會(huì)為每一個(gè)input生成一個(gè)子scope對(duì)象,而$parent表示用父類的scope,這樣我們?cè)贘S文件中才能取到該值。
- $index代表的意思是ng-repeat="param in params"遍歷時(shí)的下標(biāo)
- conf是我們?cè)趈s中的變量名實(shí)際效果
我們?cè)赾ontroller中定義了一個(gè)$scope.conf = [];就是一個(gè)數(shù)組,剛好通過上面的代碼,為該數(shù)組添加了元素,然后我們通過scope.conf剛好把ng-model的所有元素自動(dòng)保存了。
實(shí)際效果:
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
AngularJs Understanding the Controller Component
本文主要介紹AngularJs Understanding the Controller Component的內(nèi)容,這里整理了相關(guān)資料,及簡(jiǎn)單示例代碼,有興趣的小伙伴可以參考下2016-09-09AngularJS框架中的雙向數(shù)據(jù)綁定機(jī)制詳解【減少需要重復(fù)的開發(fā)代碼量】
這篇文章主要介紹了AngularJS框架中的雙向數(shù)據(jù)綁定機(jī)制,結(jié)合實(shí)例形式分析了AngularJS雙向數(shù)據(jù)綁定機(jī)制的原理及實(shí)現(xiàn)方法,以及減少需要重復(fù)開發(fā)代碼量的優(yōu)勢(shì),需要的朋友可以參考下2017-01-01使用 Github Actions 自動(dòng)部署 Angular 應(yīng)用到 Github Pages的方法
這篇文章主要介紹了使用 Github Actions 自動(dòng)部署 Angular 應(yīng)用到 Github Pages,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07從?Angular?Route?中提前獲取數(shù)據(jù)的方法詳解
這篇文章主要介紹了從?Angular?Route?中提前獲取數(shù)據(jù),通過本文,你將學(xué)會(huì)使用?resolver,?在?Angular?App?中應(yīng)用?resolver,應(yīng)用到一個(gè)公共的預(yù)加載導(dǎo)航,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07AngularJS實(shí)現(xiàn)的回到頂部指令功能實(shí)例
這篇文章主要介紹了AngularJS實(shí)現(xiàn)的回到頂部指令功能,結(jié)合實(shí)例形式分析了AngularJS返回到頂部功能的具體步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-05-05仿Angular Bootstrap TimePicker創(chuàng)建分鐘數(shù)-秒數(shù)的輸入控件
這篇文章主要為大家詳細(xì)介紹了仿Angular Bootstrap TimePicker創(chuàng)建分鐘數(shù)-秒數(shù)的輸入控件的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-07-07詳解在AngularJS的controller外部直接獲取$scope
本篇文章主要介紹了詳解在AngularJS的controller外部直接獲取$scope ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06