先日作った RedmineTimeTracker というChromeAppでAngularJSからGoogle Analyticsを使うためのモジュールを作ったのでメモ。
背景
作っていたアプリで Google Analytics を使おうと思ったのだけれど、このアプリでは AngularJSを使っている。そうするとButtonタグとかクリックイベントのついたタグが動的に追加・削除されるので、idを指定してクリックイベントへ Google Analytics のコードをバインド、というのができない。
調べたらライブラリはいくつか見つかったのだけれど、トラッキングしたいだけなのになんだか面倒。
と思ったので作りました。
作ったモジュール
analytics.coffee
angular.module('analytics', [])
.factory 'Analytics', ['$log', ($log) ->
_service = null
_tracker = null
return {
###*
Set parameter, and initialize.
@method init
@param param {Object} Parameter for Initialize (required).
@param param.serviceName {String} service name (required).
@param param.analyticsCode {String} google analytics code (required). ex) UA-32234486-7
###
init: (param) ->
_service = analytics.getService(param.serviceName)
_tracker = _service.getTracker(param.analyticsCode)
###*
Track a click on a button using the asynchronous tracking API.
@method sendEvent
@param category {String} The name you supply for the group of objects you want to track (required).
@param action {String} A string that is uniquely paired with each category, and commonly used to define the type of user interaction for the web object (required).
@param label {String} An optional string to provide additional dimensions to the event data (optional).
@param value {Integer} An integer that you can use to provide numerical data about the user event (optional).
###
sendEvent: (category, action, label, value) ->
if not _tracker
$log.error "please init analytics."
return
_tracker.sendEvent category, action, label, value
###*
Track a view using the asynchronous tracking API.
@method sendView
@param viewName {String} view's name which will be tracked.
###
sendView: (viewName) ->
if not _tracker
$log.error "please init analytics."
return
_tracker.sendAppView viewName
###*
Set Tracking is permitted.
@method setPermission
@param permitted {Boolean} Is enable tracking.
###
setPermission: (permitted) ->
if not _service
$log.error "please init analytics."
return
_service.getConfig().addCallback (config) ->
config.setTrackingPermitted(permitted)
}
]
ga-click.coffee
myApp.directive 'gaClick', (Analytics) ->
return {
restrict: 'A'
link: (scope, element, attrs) ->
element.on 'click', () ->
Analytics.sendEvent 'user', 'clicked', attrs.gaClick
}
使い方
直接使う感じ。
angular.module('myApp', ['analytics'])
.controller 'MainCtrl', (Analytics) ->
# 初期化
Analytics.init {
serviceName: "MyApplicationName"
analyticsCode: "UA-32234486-7"
}
# 画面更新
Analytics.sendView("/app/")
DirectiveとしてHTMLに記述する感じ。
<div ng-click="clickButton()" ga-click="clickButton" class="button">
・・・
</div>
感想
なんかモジュール化しておくとパッと使えそうで便利な感じ。
とはいえ、Directiveにするとタグごとに記載しないと行けなくてすごく面倒だ。
ng-clickを拡張するとかできないのかぁ?