Angular JS:错误:[ngRepeat:dupes]带有ng-repeat

时间:2017-06-15 07:27:50

标签: angularjs

我正在尝试使用跟踪错误的对象,因为我有重复键。我要做的就是初始化带有选项的选择框。

HTML:

<md-select ng-model="$ctrl.metric">
   <md-option ng-value="opt.value" ng-repeat="opt in $ctrl.obj track by opt.value">
      {{opt.label}}
   </md-option>
</md-select>

JS:

this.obj = {
        label: 'High',
        value: {
          $gte: 0,
          $lte: 2
        }
      },
      {
        label: 'Low',
        value: {
          $gte: 3,
          $lte: 4
        }
      }

this.metric = {
              $gte: 3,
              $lte: 4
            }

2 个答案:

答案 0 :(得分:1)

最好避免在对象上使用ng-repeat,而Xatyrian指出你不能在数组上使用track by。最好使用带有轨道的标签

&#13;
&#13;
var app = angular.module('plunker', []);

app.controller('MainCtrl', function() {

  var vm = this;

  vm.obj = [{
      label: 'High',
      value: {
        $gte: 0,
        $lte: 2
      }
    },
    {
      label: 'Low',
      value: {
        $gte: 3,
        $lte: 4
      }
    }
  ]

  vm.metric = {
    $gte: 3,
    $lte: 4
  }


});
&#13;
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl as $ctrl">
  <select ng-model="$ctrl.metric">
      <option ng-value="opt.value" ng-repeat="opt in $ctrl.obj track by opt.label">
      {{opt.label}}
   </option>
</select>

</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

继续@ User93的回答 也可以使用ng-options而不是ng-repeat。 像这样:

<body>
<div ng-controller="MainCtrl as $ctrl">
 <select ng-model="$ctrl.metric" ng-options="opt as opt.label for opt in $ctrl.obj"></select>
</div>
</body>