2015/09/30

AngularJS ng-init

ng-init可以用於設定初始值

<!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.names = ['陳', '王', '方', '林', '朱'];
    $scope.divClick = function(name, index){
     alert(name + "在陣列的位置為" + index);
    };
   });
  </script>
  <meta charset="utf8"/>
  <title>Filter</title>
 </head>
 <body ng-app="myApp">
  <div ng-controller="myController">
   <div ng-repeat="name in names" ng-init="nameIndex=names.indexOf(name)" ng-bind="name" ng-click="divClick(name, nameIndex)"></div>
  </div>
 </body>
</html>

執行結果: