AngularJS - 在ng-repeat内选择set的默认值

时间:2015-05-06 21:48:31

标签: javascript angularjs select angularjs-ng-repeat

我正面临AngularJS的问题 - 我无法在<select>中显示所选值。

这是我的用例:

我有一个以ng-repeat开头的视图来显示组件。每个组件都包含一个选择以选择增值税率。创建新项目时,它看起来很好。但是当我编辑现有项目时,实际的vatRate代码不会显示在选择中,而是会看到默认选项“ - 选择增值税率 - ”而不是选定的增值税。

我的模型仅包含增值税的ID。

使用单个组件我可以使用$ scope中的变量来设置当前项值,但是在这里我可以有多个组件,每个组件都有自己的增值税率,所以我不知道这是怎么做到的:

这是我的代码

<div ng-repeat="i in items">
   <label>{{i.id}}</label>
   <input ng-model="i.title">
   <select ng-model="i.vatRateId">
      <option value="">--- Select an option ---</option>
      <option ng-repeat="value in vatRates"
              ng-selected="i.vatRateId == value.id"
              value="{{value.id}}">{{value.value}}     
      </option>
   </select>
</div>

对象:

$scope.vatRates = [
    { 'id': 1, 'value' : '20' },
    { 'id': 2, 'value' : '10' },
    { 'id': 3, 'value' : '7' }
];

$scope.items = [
    { 'id': 1, 'title' : 'Title1', 'vatRateId' : '1' },
    { 'id': 2, 'title' : 'Title2', 'vatRateId' : '2' },
    { 'id': 3, 'title' : 'Title3', 'vatRateId' : '3' }
];

这是一个现场演示来解释我的问题:

Demo on PLNKR

我无法在选择正确的值中设置每个项目。

4 个答案:

答案 0 :(得分:27)

我对您的要求不是很清楚,但如果您想要将默认选定值显示为<select>,则可以使用 ng-selected 。要使用此功能,您需要在控制器中将默认选定值作为模型添加到<select>,并将ng选择添加到<options ng-selected="{{defaultvalue == value.id}}" ng-repeat="value in vatRates"> }

对于代码和参考我只是改变了你的plunker,

http://embed.plnkr.co/ZXo8n0jE8r3LsgdhR0QP/preview

希望这有帮助。

答案 1 :(得分:9)

您应该通过控制器而不是ng-init在ng-model上设置默认值。来自docs

  

ngInit的唯一合适用途是用于别名ngRepeat的特殊属性,如下面的演示所示。除了这种情况,您应该使用控制器而不是ngInit来初始化作用域上的值。

     

— AngularJS ng-init Directive API Reference - Overview

&#13;
&#13;
angular.module('app', [])
.controller('SelectController', function() {

    var selectCtrl = this;
  selectCtrl.values = ["Value 1", "Value 2", "Value 3"];
  selectCtrl.selectedValue = "Value 1";
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="SelectController as selectCtrl">
<select ng-model="selectCtrl.selectedValue"> 
  <option ng-repeat="value in selectCtrl.values" value="{{value}}">{{value}}     </option> 
  </select>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

<select ng-model="val" ng-init="myval = vals[0]">
    <option ng-repeat="myval in vals" value="{{myval.value}}">{{val.name}}
    </option>
</select>

答案 3 :(得分:2)

This is the only way i managed to do it, and its done when another select is changing. (maybe thats the cause other solutions don't work, please note the extra ""+ to force it to be a string. (otherwise not working)

In the controller:

$scope.formData.number_of_persons = "̲"̲+̲ $scope.numberOfPersons[0].val;

HTML:

<select name="number_of_persons" 
        id="number_of_persons" 
        ng-model="formData.number_of_persons" 
        required>
    <option ng-repeat="option in numberOfPersons" value="{{option.val}}">
        {{option.val}}
    </option>
</select>
相关问题