具有选项和对象比较的角度选择标记

时间:2014-06-18 21:24:52

标签: javascript angularjs

我正在尝试使用预先选择的值设置<select>标记。不幸的是,我无法使用ng-options指令,因为ui-select2 module不支持它。

以下是一个示例(或as a Plunker if you would prefer):

// Controller
$scope.colors = [{
  name: 'blue',
}, {
  name: 'red',
}, {
  name: 'green'
}];

$scope.selectedColor = $scope.colors[0];


<!-- HTML -->
<select ng-model="selectedColor">
  <option ng-repeat="color in colors" value="{{color}}">{{color.name}}</option>
</select>

在这种情况下,我希望angular能够意识到$scope.selectedColor与第一个颜色对象是同一个对象并正确预选,但它似乎不起作用。

我可以使用ng-options或按名称进行比较来解决此问题,但这些解决方案都不理想。

如何在Angular选择中正确比较对象?

1 个答案:

答案 0 :(得分:0)

我在网上找到了一个似乎使用ng-optionsui-select2的示例,它似乎可以满足您的需求。请参阅Plunker here

HTML

<select ui-select2
    ng-model="selectedColor"
    ng-options="color.name for color in colors">
</select>

控制器

$scope.colors = [
{
    name: 'blue',
},
{
    name: 'red',
},
{
    name: 'green'
}];

$scope.selectedColor = $scope.colors[1];