AngularJS 獲取ng-repeat動態(tài)生成的ng-model值實例詳解
AngularJS 獲取ng-repeat動態(tài)生成的ng-model值
最近做項目遇到了ng-model是ng-repeat動態(tài)生成的,ng-model=”變量”,什么變量,是未知的,所以你無法在$scope."變量"取到值,就算取到值也是其中一個值,這樣的問題,經(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()"> 應用 </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'); }; };
問題描述
因為ng-model是ng-repeat動態(tài)生成的,ng-model=”變量”,什么變量,是未知的,所以你無法在$scope."變量"取到值,就算取到值也是其中一個值,這個問題困擾了我一天,終于解決了。
解決方法
首先ng-model設置為$parent.conf[$index]:
- 用$parent的原因是ng-repeat產(chǎn)生的,他會為每一個input生成一個子scope對象,而$parent表示用父類的scope,這樣我們在JS文件中才能取到該值。
- $index代表的意思是ng-repeat="param in params"遍歷時的下標
- conf是我們在js中的變量名實際效果
我們在controller中定義了一個$scope.conf = [];就是一個數(shù)組,剛好通過上面的代碼,為該數(shù)組添加了元素,然后我們通過scope.conf剛好把ng-model的所有元素自動保存了。
實際效果:
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
AngularJs Understanding the Controller Component
本文主要介紹AngularJs Understanding the Controller Component的內(nèi)容,這里整理了相關資料,及簡單示例代碼,有興趣的小伙伴可以參考下2016-09-09AngularJS框架中的雙向數(shù)據(jù)綁定機制詳解【減少需要重復的開發(fā)代碼量】
這篇文章主要介紹了AngularJS框架中的雙向數(shù)據(jù)綁定機制,結合實例形式分析了AngularJS雙向數(shù)據(jù)綁定機制的原理及實現(xiàn)方法,以及減少需要重復開發(fā)代碼量的優(yōu)勢,需要的朋友可以參考下2017-01-01使用 Github Actions 自動部署 Angular 應用到 Github Pages的方法
這篇文章主要介紹了使用 Github Actions 自動部署 Angular 應用到 Github Pages,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07從?Angular?Route?中提前獲取數(shù)據(jù)的方法詳解
這篇文章主要介紹了從?Angular?Route?中提前獲取數(shù)據(jù),通過本文,你將學會使用?resolver,?在?Angular?App?中應用?resolver,應用到一個公共的預加載導航,本文給大家介紹的非常詳細,需要的朋友可以參考下2022-07-07仿Angular Bootstrap TimePicker創(chuàng)建分鐘數(shù)-秒數(shù)的輸入控件
這篇文章主要為大家詳細介紹了仿Angular Bootstrap TimePicker創(chuàng)建分鐘數(shù)-秒數(shù)的輸入控件的相關資料,感興趣的小伙伴們可以參考一下2016-07-07詳解在AngularJS的controller外部直接獲取$scope
本篇文章主要介紹了詳解在AngularJS的controller外部直接獲取$scope ,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06