AngularJS1.5に再挑戦 その11 ngClick & confirmClick Directives
概要
AngularJS1.5に再挑戦 その11 ngClick & confirmClick Directives
参考動画・参考サイト
AngularJS — Superheroic JavaScript MVW Framework
ngClick & confirmClick Directives
- ngClickを使ってみる。ngClickの詳しい解説は以下の通り。
- blog-list.htmlを修正する。ng-clickを定義する。ここでは、contextとしてgoToItem()というファンクションを代入しているので、goToItem()をclick-confirm.directives.jsで定義する。
<a ng-href='/blog/{{ item.id }}' ng-click='goToItem()' />{{ item.title }} {{ item.publishDate }}</a>
- goToItem()は、blog-list.components.jsで定義するらしい。
'use strict'; angular.module('blogList'). component('blogList', { templateUrl: '/templates/blog-list.html', controller: function(Post, $routeParams, $scope){ $scope.goToItem = function(){ console.log("some item") }; $scope.items = Post.query(); } });
- 再度blog-list.htmlを修正する。
<a href='#' ng-click='goToItem(item)' />{{ item.title }} {{ item.publishDate }}</a>
- またblog-list.components.jsを編集する。コードの追記内容は、goToItemをcontextとして渡すことを目的としている。
'use strict'; angular.module('blogList'). component('blogList', { templateUrl: '/templates/blog-list.html', controller: function(Post, $location, $routeParams, $rootScope, $scope){ // function(post) == goToItem(post)のため、htmlでは、postの箇所にオブジェクトを渡す。 $scope.goToItem = function(post){ // locationで、/blog/post.idにアクセスせよという指示 $location.path("/blog/" + post.id) // $rootScope.$apply(function(){ // }) }; $scope.items = Post.query(); } });
- blog-list.htmlもいかのように修正する。
<h1>Blog List</h1> <ul ng-if='items.length > 0'> <li ng-repeat='post in items'> <a ng-href='/blog/{{ post.id }}' confirm-click='Are you ready?' confirmed-click='goToItem(post)' />{{ post.title }} {{ post.publishDate }}</a> <!-- <a href='#' ng-click='goToItem(post)' />{{ post.title }} {{ post.publishDate }}</a> --> <!-- <confirm-click message='メッセージ!' eq='10+100+10' post='item'></confirm-click> --> </li> </ul> <span ng-if='items.length == 0'>Posts coming soon</span>
- ただ、このままでは、comfirmしてもしなくても、ページ遷移してしまう。click-confirm.direcitive.jsをクリックした時のデフォルトアクションを停止する設定を追記する。
'use strict'; angular.module('confirmClick'). directive('confirmClick', function(){ return { restrict: "A", link: function(scope, element, attr){ var msg = attr.confirmClick || "Are you Sure?"; var clickAction = attr.confirmedClick; element.bind("click", function(event){ event.stopImmediatePropagation(); event.preventDefault() if (window.confirm(msg)){ scope.$eval(clickAction) } else { console.log("Canceled") } }); } } });
これで、できるようになった!でも仕組みはさっぱりわからんな(^ ^;)ということで、これは参考書でちゃんと復習しておこう。
全体の流れは、デフォルトのアクションを停止して、特定のアクションが行われた時だけ、clickactionが呼び出されるようにするという仕様だと思われる。そうする方が、特定の機能を停止させるよりも楽なのかもしれない。