AngularはHTMLの中にng-clickなどと書いておけばイベントを紐づけて、特定動作時にメソッドを呼び出すことができます。
これをオリジナルで自作することができます。
customer_directive.js
1 2 3 4 5 6 |
var appDirective = angular.module('appDirective', []) .directive('myDirective', function(){ return { template: '<p>本日は晴天なり</p>' }; }); |
index.html
1 2 3 4 5 6 7 8 9 10 |
<html ng-app="appDirective"> <head> <script type="text/javascript" src="angular.min.js"></script> <script type="text/javascript" src="customer_directive.js"></script> </head> <body> <div my-directive></div> <!-- ここにカスタムディレクティブで指定したHTMLが表示されます。 --> </body> </html> |
これを踏まえて、例えばある入力欄でEnterキーを押したときに特定のクラスをもった入力欄に移動するというイベントをHTML要素に付与したいとします。
主に入力欄が表のようになっているテーブル形式のHTMLを考えます。
1 2 3 4 5 6 |
<tr> <td><input type="text" class="move_target" value="" name="hoge1" move-focus></td> </tr> <tr> <td><input type="text" class="move_target" value="" name="hoge2" move-focus></td> </tr> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var appDirective = angular.module('appDirective',[]) .directive('moveFocus', function(){ return function(scope, element, attrs) { element.bind("keydown keypress", function (event) { var targetElementsCondition = "input.move_target"; var keyCode = event.which || event.keyCode; if ( keyCode === 13 ) { //移動対象の要素をこれで取得します。 var $list = $(targetElementsCondition); //自分の番地はindex(this)で判定します。 var num = $list.index(this); var target = num + 1; if( target < $list.length ){ //これが移動したい先のhtml $list[target].select(); event.preventDefault(); } } }); }; }); |