0

当页面加载时,我无法将选择框的初始选项“选中”。

在 Plunker 中查看代码

正如您在 plunker 中看到的,选择器在加载时是空白的,但是交易模型是使用默认类别值初始化的。我确定我错过了一些愚蠢的东西,但是为什么选择框没有初始值?

看法:

<p>Category: {{deal.category.name}}</p>

<select ng-model="deal.category" ng-options="category.name for category in categories"></select>

控制器:

app.controller("MyCtrl", function($scope) {

  // An object with a predefiend category.
  $scope.deal = {"category":{"_id":"1","name":"Music/Media","value":1}};

  // List of available categories
  $scope.categories = [{"_id":"1","name":"Music/Media","value":1},{"_id":"2","name":"Weather","value":2},{"_id":"3","name":"Navigation"}];
});


更新:

我创建了一个简化版本,但实际数据来自资源。所以控制器实际上看起来更像这样:

$scope.deal = getDeal();
$scope.categories = Category.query();

但是,我的示例中的 JSON 完全相同。

如果我实现 Davin Tryon 或 Sza 的示例,那么我将不得不这样做:

$scope.categories = Category.query(function() {
  for(var i = 0; i < $scope.categories.length; i++) {
    if($scope.categories[i]._id == $scope.deal.category._id) {
      $scope.deal.category = $scope.categories[i];
    }
  }
});

这对我来说似乎有点奇怪,还有其他方法吗?

4

2 回答 2

1

由于 AngularJS 需要通过引用检测模型对象与下拉列表中的对象是否相等,因此您需要使用与预选项目相同的对象,而不是创建新对象。

这将修复代码:

$scope.categories = [{"_id":"1","name":"Music/Media","value":1},{"_id":"2","name":"Weather","value":2},{"_id":"3","name":"Navigation"}];
$scope.deal = {"category":$scope.categories[0]};
于 2013-09-04T21:09:11.433 回答
0

默认情况下,ng-options 将使用对象引用,因此您必须从列表中选择类别。

因此,您可以将控制器更改为:

  $scope.categories = [{"_id":"1","name":"Music/Media","value":1},{"_id":"2","name":"Weather","value":2},{"_id":"3","name":"Navigation"}];

  $scope.deal = $scope.categories[0];

这是一个更新的 plunker

于 2013-09-04T21:09:31.490 回答