こんにちは、こんばんわ、お久しぶりです。
NHN Japan ウェブサービス本部開発1室UITチーム 吉田徹生(@teyosh)と申します。
3ヶ月ぶりの登場です。
AngularJSって何?という方は第一回目の記事[Angular JSを使おう]を御覧ください。
さて、3ヶ月の間にstableは1.0.5と順調にアップデートしております。
ちゃんとアップデートがされると使っていても安心できます。
今回はAngularJSを利用していると気になるng-clickやng-repaeatなどAttributeに設定されているものについてです。
これはdirectiveの拡張でAngularが機能を設定してくれます。
Hello, World
以下のようなコードがあるとします。
<div ng-app='hello'> <div ng-controller='helloCtrl'> <button ng-click='hello("world")'>hello</button> </div> </div>
angular.module("hello", []); function helloCtrl($scope){ $scope.hello = function(str) alert("hello, "+ str); } }
サンプル
これはbuttonをクリックするとhello, worldとalertが出ます。
では、directiveを使って作ってみます。
<div ng-app='hello'> <div> <button hello='world'>hello</button> </div> </div>
var app = angular.module('hello', []); app.directive("hello", function(){ return function(scope, element, attr){ element[0].addEventListener("click", function(){ alert("hello, "+ attr["hello"]); }); }; });
サンプル
これはhtmlにng-clickを設定せずにdirectiveでaddEventListenerを指定しています。
このような書き方も出来ます。
<div ng-app='hello'> <div hello='world'></div> </div>
var app = angular.module('hello', []); app.directive("hello", function(){ return { restrict : 'A', link : function(scope, element, attr){ scope.hello = function(){ alert("hello, "+ attr["hello"]); }; }, template : '<button ng-click="hello()">hello</button>' }; });
directiveで指定したelementにtemplateを追加してeventを設定しています。
returnで返しているオブジェクトは
・restrictは’A’ => Attribute, ‘E’ => Element, ‘C’ => Class がありdirective名を指定する場所を設定します。EはIEのバージョンによってはエラーになってしまいますので注意が必要です。
・linkはdirectiveが展開された時に発火されます。
・templateはdirectiveを設定してるエレメントの子要素に追加されます。
簡単なサンプルでしたが如何でしたか?
directiveを使えばhtmlが見やすくなり保守性を高める事が出来るかと思います。
また、moduleを切り分ければ再利用もしやすくなります。
他にもscopeの処理やtemplate urlの使用など色々とできます。
開発ガイド(英語)かAngularJS Japan User Groupへどうぞ。