选择AngularJS选项



我知道有很多问题,但我有最烦人的时间弄清楚AngularJS如何处理选择选项值,哪一个被选中。我有一个简单的项目,我传递到一个模态窗口。此项目包含template_id。我也有templates有一个名称和一个id,我希望创建一个简单的选择,其中有项目的template_id值的选项被选中:

<select name="templateId">
  <option value="8000">name</option>
  <option value="8001" selected>name 2</option>
</select>
在AngularJS中,我这样做:
<select name="templateId"
    ng-model="domain.templateId"
    ng-options="t.template_id as t.name for t 
                in templates track by t.template_id">
      <option value="">Choose template</option>
 </select>

在控制器中,我设置了'selected'值:

Data.get('templates').then(function(result) {
    $scope.templates = result;
});
$scope.domain = {
    template_id: item.template_id,
    templateId: { template_id: item.template_id }
};

我实际上已经到了一个点,我可以发送template_id到REST API那里的响应读取

template_id: 8000
然而,在select元素中有一些小的令人讨厌的行为。我得到了我想要选择的项目,但当我尝试选择另一个选项时,它将选择切换到预设的"选择模板"选项,但值或更确切地说,"真正选择的项目"仍然是我在控制器中设置的原始"选择"值。我可以在REST API响应中看到它。然而,这并不是我所选择的。在这个最初的bug之后,它继续工作,因为它应该,但我怎么能摆脱这个?

这里有一个例子可以解决你的问题。

angular.module('app.select', [])
  .controller('SelecetCtrl', function($scope) {
    $scope.templates = [{
      template_id: 1,
      name: 'tst1'
    }, {
      template_id: 2,
      name: 'tst2'
    }, {
      template_id: 3,
      name: 'tst3'
    }];
    $scope.selected = {
      template: {
        template_id: 2
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app.select'>
  <div ng-controller='SelecetCtrl'>
    <select name="templateId" ng-model="selected.template" 
            ng-options="t as t.name for t 
                in templates track by t.template_id">
      <option value="">Choose template</option>
    </select> 
  </div>
</div>

最新更新