使用ng-repeat和$ index如何设置select中选择的默认值

时间:2016-09-29 06:10:28

标签: angularjs select

使用ng-repeat和$ index如何使用angularjs显示默认选定值

我的代码: 我有SelectValues:

"Jewelery_And_Diamond_Type": [
{
  "id": 33, 
  "value": "Earrings"
}, 
{
  "id": 35, 
  "value": "Gemstones"
}, 
{
  "id": 34, 
  "value": "Loose Diamonds"
}, 
{
  "id": 32, 
  "value": "Necklaces"
}, 
{
  "id": 31, 
  "value": "Pendants"
}, 
{
  "id": 30, 
  "value": "Rings"
} ]

selected Value is "Earings"

在我的HTML中

 <select ng-model="categoryval.Jewelery_And_Diamond_Type[$index]" ng-init="categoryval.Jewelery_And_Diamond_Type[$index] = SelectValues.Jewelery_And_Diamond_Type.indexOf(0)" ng-options="option.value for option in SelectValues.Jewelery_And_Diamond_Type track by option.id">

如果我这样写,则表示默认情况下没有选择任何值。我需要基于$ index的精确选择的值。

4 个答案:

答案 0 :(得分:1)

使用ng-options

 <select ng-model="value" ng-init="value='Earrings'"   ng-options="mode.value as mode.value for mode in storageResult.Jewelery_And_Diamond_Type">
  </select>

DEMO

答案 1 :(得分:0)

如果你知道默认选择值可用的id,你可以将它包含在范围变量中并注入变量

<option value="">{{selectedType}}</option>

$scope.selectedType= categoryval.Jewelery_And_Diamond_Type[defaultIndex].valu‌​e

value =&#34;&#34;帮助您填补空的第一个选项

答案 2 :(得分:0)

在选择中,ng-model将确定选择了哪个选项。

因此,如果您想严格按照数组中的索引选择项目,则需要创建对象模型,如下所示:

$scope.selected = $scope.values[0];

值是你的json数组。

选择将如下所示:

    <select
      ng-model="selected"
      ng-options="option.value for option in values track by option.id">
   </select>

不要在HTML中使用ng-init,这是不好的做法。

&#13;
&#13;
function MyController() {
    this.values =  [
    {
      "id": 33, 
      "value": "Earrings"
    }, 
    {
      "id": 35, 
      "value": "Gemstones"
    }, 
    {
      "id": 34, 
      "value": "Loose Diamonds"
    }, 
    {
      "id": 32, 
      "value": "Necklaces"
    }, 
    {
      "id": 31, 
      "value": "Pendants"
    }, 
    {
      "id": 30, 
      "value": "Rings"
    } ];
    this.selected = this.values[0];
  };

angular.module('app', []);
angular.module('app')
  .controller('MyController', MyController);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="MyController as ctrl">
    <select
        ng-model="ctrl.selected"
        ng-options="option.value for option in ctrl.values track by option.id">
    </select>
    <br>
    {{ctrl.selected | json}}
  </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

删除ng-init并在控制器中设置默认值,以便您可以单独测试默认选项是否始终是您想要的。

在控制器中:

$scope.defaultValue =  $scope.SelectValues.Jewelery_And_Diamond_Type[0];

然后更改HTML

<select ng-model="defaultValue"  ng-options="option.value for option in SelectValues.Jewelery_And_Diamond_Type track by option.id">

Plunker

相关问题