如何将角度设置为组合框的初始值?

时间:2014-05-08 09:37:45

标签: javascript angularjs combobox

如果我想设置组合框的值,我试过这个:

controllercode:

 $scope.streettypeMockData = [{
    name: 'Street',
    value: 'Street'
  }, {
    name: 'Avenue'
  }, {
    name: 'Crescent'
  }, {
    name: 'Drive'
  }, {
    name: 'Road'
  }, {
    name: 'Highway'
  }];

  var sel = "Street";
  var selectedValue = {
    name: sel
  };
  $scope.streetTypeSelected = selectedValue;

谁能告诉我为什么这不起作用?另见http://plnkr.co/edit/4ISL8A1cNGCtafsc0leX?p=preview

2 个答案:

答案 0 :(得分:0)

您可以像这样简单地使用ng-init

<select ng-init="streetTypeSelected = streettypeMockData[0]" class="form-control" ng-model="streetTypeSelected" ng-options="streetType.name for streetType in streettypeMockData">
  </select>

<强> Working Demo

你也可以这样做,如下所示

var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
     $scope.streettypeMockData = [
        {name: 'Street', value: 'Street'},
        {name: 'Avenue'},
        {name: 'Crescent'},
        {name: 'Drive'},
        {name: 'Road'},
        {name: 'Highway'}
    ];
    $scope.streetTypeSelected = $scope.streettypeMockData[0];
});

<强> Working Demo

另外看看这个

https://docs.angularjs.org/api/ng/directive/select

答案 1 :(得分:0)

代码有一些问题:

  • ng-options选择名称,而ng-model指向对象。最好使用streetType as streetType.name for streetType in streettypeMockData来选择整个对象。
  • 在这种情况下,初始值将不受尊重,因为Angular将尝试通过引用比较对象;使用track by

完整<select>应为:

    <select class="form-control" ng-model="streetTypeSelected"
      ng-options="streetType as streetType.name for streetType in streettypeMockData track by streetType.name">

请参阅forked plunker