选择AngularJS选项

时间:2015-07-13 09:09:55

标签: javascript 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>

在控制器中,我设置了&#39;选择&#39;价值:

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元素中存在一些轻微的恼人行为。我得到了我想要的项目,但当我尝试选择其他选项时,它会将所选项目切换到预设的“选择模板”。选项但是价值或者更确切地说是真正选择的项目&#39;仍然是最初的选择&#34;我在控制器中设置的值。我可以在REST API响应中看到它。然而,这不是我选择的。在这个最初的错误之后,它继续按照它应该的方式工作,但我怎么能摆脱这个呢?

1 个答案:

答案 0 :(得分:0)

这是一个解决问题的例子。

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>

相关问题