加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS中获取ng-repeat动态生成的ng-model值

发布时间:2020-12-17 10:33:03 所属栏目:安全 来源:网络整理
导读:angularJS动态设置model,并设置/获取model的值 代码 html div div class = "modal-header" h3 class = "modal-title" 用例集全局参数配置 / h3 / div div class = "modal-body" table class = "table table-hover" thead tr th 参数 / th th 参数值 / th /

angularJS动态设置model,并设置/获取model的值

代码

html

<div>
    <div class="modal-header">
        <h3 class="modal-title">用例集全局参数配置</h3>
    </div>
    <div class="modal-body">
        <table class="table table-hover">
            <thead>
            <tr>
                <th>参数</th>
                <th>参数值</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-modelng-repeat动态生成的,ng-model=”变量”,什么变量,是未知的,所以你无法在$scope."变量"取到值,就算取到值也是其中一个值,这个问题困扰了我一天,终于解决了。

解决方法

首先ng-model设置为$parent.conf[$index]:

  • $parent的原因是ng-repeat产生的,他会为每一个input生成一个子scope对象,而$parent表示用父类的scope,这样我们在JS文件中才能取到该值。
  • $index代表的意思是ng-repeat="param in params"遍历时的下标
  • conf是我们在js中的变量名

我们在controller中定义了一个$scope.conf = [];就是一个数组,刚好通过上面的代码,为该数组添加了元素,然后我们通过scope.conf刚好把ng-model的所有元素自动保存了。

实际效果

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读