【问题标题】:dynamically setting ng-model name when using ng-repeat (or how to use ng-repeat item value as ng-model name)使用 ng-repeat 时动态设置 ng-model 名称(或如何使用 ng-repeat 项目值作为 ng-model 名称)
【发布时间】:2018-04-10 14:56:46
【问题描述】:

我有一些基于 ng-repeat 动态生成的字段。但是我需要为这些字段动态设置 ng-model 名称,这应该基于 ng-repeat 中的 $index 或者它应该将 ng-repeat 项目值作为 ng-model 的名称。

下面是我的代码

 <div class="panel-body"
                        data-ng-controller="XModelController as xmdlCtrl">

 ................

 ................

 <th data-ng-repeat="item in ['xmdlCtrl.rsptYrs.year1Date', 'xmdlCtrl.rsptYrs.year2Date', 'xmdlCtrl.rsptYrs.year3Date', 'xmdlCtrl.rsptYrs.year4Date', 'xmdlCtrl.rsptYrs.year5Date', 'xmdlCtrl.rsptYrs.year6Date'] | limitTo: xmdlCtrl.colCount"><section col col-11>Year{{$index+1}}</section>

 <section col col-11>
   <label class="input"> <input id="year{{$index+1}}" 
          placeholder="MMM-YYYY" required="required" data-ng-model="'xmdlCtrl.rsptYrs.year{{$index+1}}Date" /</label></section></th>

 ........................

上面的代码在执行时会产生一个令牌错误,因为它不允许'{{}}'

我的实际要求是我希望 ng-model 具有以下名称

ng-model="xmdlCtrl.rsptYrs.year1Date" ng-model="xmdlCtrl.rsptYrs.year2Date"

基于 ng-repeat 的 $index 值等等(这实际上等于xmdlCtrl.rsptYrs.year($index+1)Date

我浏览过类似的帖子,但似乎都没有一个准确的解决方案。

【问题讨论】:

  • 试试这个:data-ng-model="xmdlCtrl.rsptYrs['year' + ($index+1) + 'Date']"
  • @SlavaUtesinov 感谢您的回复,但这会导致:[$parse:syntax] 语法错误:令牌 '[' is not a valid identifier at.. 错误
  • eccentricCoder,它正在工作,正如您在我的回答中看到的那样。我假设你使用太旧的 AngularJS 版本。
  • @SlavaUtesinov Harpreet 您的两种解决方案都运行良好。非常感谢。

标签: angularjs


【解决方案1】:

angular.module('app', []).controller('ctrl', function($scope){
  $scope.items = [{test1: 1}, {test2: 1}]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='ctrl'>
  <input ng-repeat-start='item in items' ng-model="item['test' + ($index + 1)]" type='number'/>  
  <br ng-repeat-end>
  {{items | json}}
</div>

【讨论】:

  • @eccentricCoder,你应该创建 plunker 来重现你的问题。
  • 非常感谢。你拯救了我的一天。该代码运行良好,没有任何问题。这似乎是一些缓存问题。 (我仍然不知道为什么它以前不起作用)我正在删除我以前的 cmets,我说它不起作用,因为它应该在那时起作用。非常感谢。
  • 如果你不介意你能解释一下这是如何工作的(我没有清楚地理解它是如何工作的),因为正如我所提到的,我的 ng-model 名称是 xmdlCtrl.rsptYrs.year2Date 和模型名称有效的是 data-ng-model="xmdlCtrl.rsptYrs['year' + ($index+1) + 'Date']" 缺少'。 ' 运算符
  • @eccentricCoder,您只是使用了rsptYrs.year{{$index+1}}Date 而不是rsptYrs['year' + ($index+1) + 'Date']{{}} 不能这样使用 - 在名称的属性中间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-08
相关资源
最近更新 更多