ng-options默认选中

第一种方法:绑定类型 => $scope.a

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://cdn.bootcss.com/angular.js/1.6.6/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
  <select ng-init="selectPerson=persons['caohui']" ng-model="selectPerson"
          ng-options="x for (x,y) in persons">
  </select>
  <p>
    年龄:{{selectPerson.age}}
  </p>
  <p>
    性别:{{selectPerson.sex}}
  </p>
  <p>
    月薪:{{selectPerson.salary}}
  </p>
</div>
<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl',
    function($scope) {
      $scope.persons = {
        张三: {
          age: 27,
          sex: 'male',
          salary: 10000
        },
        王二: {
          age: 20,
          sex: 'male',
          salary: 500
        },
        李四: {
          age: 24,
          sex: 'female',
          salary: 6000
        }
      }
    })
</script>
</body>

</html>

第二种方法:绑定类型 => $scope.app.a

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-select-ngrepeat-production</title>
  <script src="https://cdn.bootcss.com/angular.js/1.5.0/angular.min.js"></script>
  <script>
    angular.module('ngrepeatSelect', [])
      .controller('ExampleController', ['$scope', function($scope) {

        $scope.selectIndex = {a: 1};
        $scope.arr = [
          {a: '1', value: ' A'},
          {a: '2', value: ' B'},
          {a: '3', value: 'C'}
        ];

      }]);
  </script>
</head>
<body ng-app="ngrepeatSelect">
  <div ng-controller="ExampleController">
    <form name="myForm">
      <label for="repeatSelect"> Repeat select: </label>
      <select name="repeatSelect" id="repeatSelect" ng-model="selectIndex.a">
        <option ng-repeat="option in arr" value="{{$index}}" ng-value="{{$index}}">{{option.value}}</option>
      </select>
    </form>
    <hr>
    <tt>selectIndex = {{selectIndex.a}}</tt>
    <br/>
  </div>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/chi1130/article/details/78353343