Reputation:
I am trying to use track by with object which throws above error because I have duplicates key. All I am trying to do is initialised select box with an option.
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
}
Upvotes: 1
Views: 211
Reputation: 1323
Following on from the answer by @User93
It is also possible to use ng-options
rather than ng-repeat.
Like this:
<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>
Upvotes: 1
Reputation: 1866
It is better to avoid ng-repeat on an object and As Xatyrian pointed out you cannot use track by on array. It is better to use label with track by
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
}
});
<!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="[email protected]" 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>
Upvotes: 1