2015/09/29

AngularJS ng-change

ng-change可以用在可改變選項的元素:Select、Input、Textarea


<!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.selectIndex = 0;
        $scope.score = $scope.students[0];

        $scope.myChange = function(){
           $scope.score = $scope.students[$scope.selectIndex];
        };
      });
   </script>
   <meta charset="utf8"/>
   <title>Filter</title>
  </head>
  <body ng-app="myApp">
    <div ng-controller="myController">
      <select ng-model="selectIndex" ng-change="myChange()" ng-options="students.indexOf(student) as student['Name'] for student in students"></select>
      <p ng-bind="'英文成績:' + score.En + '國文成績:' + score.Ch + '數學成績:' + score.Math"></p>
    </div>
  </body>
</html>

執行結果: