2015/09/29

AngularJS ng-options

ng-options可以在Select元素內新增Option元素
且ng-options必須搭配ng-model使用,否則將不會值新增至Select



<!DOCTYPE html>
<html>
  <head>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
   <script type="text/javascript">
    var myApp = angular.module('myApp', []);
    myApp.controller('myController', function($scope){
      $scope.students = [
      {'Name' : 'Wang', 'En' : 90, 'Ch' : 50, 'Math' : 70},
      {'Name' : 'Chen', 'En' : 30, 'Ch' : 90, 'Math' : 100},
      {'Name' : 'Fang', 'En' : 40, 'Ch' : 60, 'Math' : 10},
      {'Name' : 'Hung', 'En' : 90, 'Ch' : 90, 'Math' : 90}];

      $scope.selectIndex1 = 0;
      $scope.selectIndex2 = 0;
      $scope.selectIndex4 = 0;
    });
   </script>
   <meta charset="utf8"/>
   <title>Filter</title>
  </head>
  <body ng-app="myApp">
    <div ng-controller="myController">
      <!--沒有明確給予Value值!-->
      <select ng-model="selectIndex1" ng-options="student['Name'] for student in students"></select><br>

      <!--有明確給予Value值 且在Controller有宣告ng-model初始值!-->
      <select ng-model="selectIndex2" ng-options="students.indexOf(student) as student['Name'] for student in students"></select><br>

      <!--沒有明確給予Value值 但有預設的Option元素!-->
      <select ng-model="selectIndex3" ng-options="students.indexOf(student) as student['Name'] for student in students"><option value="">請選擇</option></select><br>

      <!--明確給予Value值 但用track沒辦法指定初始值!-->
      <select ng-model="selectIndex4" ng-options="student['Name'] for student in students track by students.indexOf(student)"></select><br>

      <!--沒有指定ng-model 不會將值新增至Select-->
      <select ng-options="student['Name'] for student in students track by students.indexOf(student)"></select>
    </div>
  </body>
</html>