Angular的select标签带有选项和对象比较

Angular select tag with options and object comparison

本文关键字:选项 对象 比较 select 标签 Angular      更新时间:2023-09-26

我正在尝试设置具有预选值的<select>标记。不幸的是,我不能使用ng-options指令,因为ui-select2模块不支持它。

这里有一个例子(或者,如果你喜欢,作为一个Plunker):

// 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选择中正确比较对象?

我在网上找到了一个例子,似乎使用ng-optionsui-select2,它似乎与你需要的工作很好。

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];