【问题标题】:Select not displaying its default value选择不显示其默认值
【发布时间】:2016-08-26 11:27:18
【问题描述】:

我有一个select,它的值是一个简单的对象。

显示为option 的内容是此对象的属性,但值是对象本身。

我正在通过将模型设置为正确的对象来为此 select 设置默认值。

但是select 没有显示任何选择的值,而模型设置正确。

我尝试了以下 3 种不同的方法:

Current value of representative.title : {{representative.title}} <br/><br />
<div class="form-group">
  <select ng-model="representative.title" 
          ng-options="title.name for title in titles" 
          ng-disabled="$parent.isDisabled" 
          class="form-control">
  </select>
</div>

<br />

<div class="form-group">
  <select ng-model="representative.title" 
          class="form-control">
    <option ng-repeat="title in titles" 
            value="{{title}}">
              {{title.name}}
    </option>
  </select>
</div>

<br />

<div class="form-group">
  <select ng-model="representative.title" 
          ng-options="title as title.name for title in titles" 
          ng-disabled="$parent.isDisabled" 
          class="form-control">

  </select>
</div>

在我的控制器中:

$scope.titles = [{"name": "Monsieur"},{"name": "Madame"}];
$scope.representative = {"title": {"name": "Monsieur"}, "otherField": "otherValue"};

为什么我的选择没有显示默认值?

我该如何解决?

(顺便说一句,我使用的是 Angular 1.2.28)

【问题讨论】:

  • {} !== {}
  • 这里可能的答案? stackoverflow.com/questions/29407513/…
  • 可能是ng-optionslabel as 可以帮助你...
  • 我在第三种情况下使用as。问题更可能来自对象相似但我认为具有不同参考的事实。我要探索这个
  • 是的,我做了这个 $scope.representative.title=$scope.titles[0];它起作用了...可能是角度不考虑 $scope.representative.title 作为标题[i]的类型。

标签: javascript html angularjs html-select


【解决方案1】:

$scope.representative = {"title": $scope.titles[0], "otherField": "otherValue"};

这会更准确,因为您需要传递选项数组中包含的对象之一的引用。

【讨论】:

  • 是的,我认为这就是问题所在。但是title实际上是从服务中设置的,所以我需要对其进行一些处理以使其等于titles的索引,这就是我现在要尝试的方法
  • 是的,就是这样,当我们将它作为参考传递时它正在工作(除了第二个选择,这可能不是一个好的角度来做)
猜你喜欢
  • 2019-12-12
  • 2020-09-21
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 2021-04-16
相关资源
最近更新 更多