欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS 获取ng-repeat动态生成的ng-model值实例详解

程序员文章站 2022-06-20 20:31:26
angularjs 获取ng-repeat动态生成的ng-model值         &...

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

              最近做项目遇到了ng-model是ng-repeat动态生成的,ng-model=”变量”,什么变量,是未知的,所以你无法在$scope."变量"取到值,就算取到值也是其中一个值,这样的问题,经过百度一番查找找到解决方案,这里记录下,也行可以帮助到大家。

代码

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-model是ng-repeat动态生成的,ng-model=”变量”,什么变量,是未知的,所以你无法在$scope."变量"取到值,就算取到值也是其中一个值,这个问题困扰了我一天,终于解决了。

解决方法

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

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

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

实际效果:

AngularJS 获取ng-repeat动态生成的ng-model值实例详解

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!