首页 > 解决方案 > AngularJS select not showing selected value

问题描述

Controller

$scope.industries= [
 {
  id: 1,
  name: "Name1", 
 }, {
  id: 2,
  name: "Name2"
 }
];

When assign $scope.filling_type = 2 in controller,I want to select "Name2" option in the select.

View

<select ng-model="filling_type">
  <option ng-repeat="industry in industries"
  ng-value="industry.name">{{industry.name}}</option>
</select>

In this case no option selected.

标签: htmlangularjs

解决方案


I'd recommend getting used to ng-options in the select element instead of ng-repeating in the option element because of increased flexibility and performance. https://docs.angularjs.org/api/ng/directive/select#choosing-between-ngrepeat-and-ngoptions-

var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
$scope.industries= [
 {
  id: 1,
  name: "Name1", 
 }, {
  id: 2,
  name: "Name2"
 }
];

$scope.filling_type = 2; // set default option here, using 2 from OP
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<body ng-app="testApp" ng-controller="testCtrl">
<select 
    ng-model="filling_type"
    ng-options="i.id as i.name for i in industries"> 
</select>
<p>Filling Type: {{filling_type}}</p>
</body>


推荐阅读