误差在选择最初选择的选项 [英] Error with the initially selected option in a select

查看:112
本文介绍了误差在选择最初选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦一个选择框的初始选项进行选择时,页面加载。

I am having trouble getting the initial option of a select box to be "selected" when the page loads.

查看code在Plunker

正如你可以在plunker看到,选择是空白的,当它加载,但交易模式,使用默认的类别值初始化。我敢肯定,我失去了一些愚蠢的,但为什么选择框没有初始值?

As you can see in the plunker, the selector is blank when it loads, however the deal model is initialized with a default category value. I'm sure I am missing something silly, but why does the select box not have an initial value?

查看:

<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"}];
});



更新:


Update:

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

I created a simplified version, however the actual data is coming from a resources. So the controller actually looks a bit more like this:

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

不过,在我的例子中,JSON是完全一样的。

However, the JSON in my example is exactly the same.

如果我实现了达文特赖恩的或SZA的例子那么我将不得不做这样的事情:

If I implement Davin Tryon's or Sza's examples then I would have to do something like this:

$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];
    }
  }
});

这似乎有点怪我,有另一种方式?

Which seems a little weird to me, is there another way?

推荐答案

由于AngularJS需要检测模型对象的平等在下拉列表中引用的对象,你需要使用完全相同的对象作为pre-选择的项目而不是创建一个新的对象。

Since AngularJS needs to detect the equality of the model object with the object in the drop down list by reference, you need to use the same exact object as the pre-selected item rather than creating a new object.

这将解决code:

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

这篇关于误差在选择最初选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆