On my angular-js application I would like track how each user uses it. Thus initially I am building a log mechanism on the client in order to track what the user clicks and then send the data onto my server.
The main question here is that I would like to log all ng-click events across my application. Is it possible to do this centralized and not have to go to each functions and add my functionality?
Ultimately I would like to include in the log message the id of the div that was clicked.
Use a directive and a service, like this:
app.directive('logClickEvent', function(Logger) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function(event) {
Logger.logEvent(event);
});
}
}
})
app.factory('Logger', function () {
return {
logEvent: function(event) {
// implement your logger logic here
}
};
});
And then place the directive on all the elements you want to log:
<button id="button1" log-click-event>button1</button>
jsFiddle: http://jsfiddle.net/bmleite/7wBsv/
option #2: 'Override' ng-click: http://jsfiddle.net/bmleite/7wBsv/2/
How about adding a click-event handler to the html body/document object and handling it that way?
Expanding on bmleite's jsFiddle - http://jsfiddle.net/w8txe/3/
The main thing is though, if logging the ID will be informative enough, and if not - how are you going to pull out the relevant information to make the logging useful?
Could always pass in $location / $rootScope / etc to pull out some more contextual information in the log handler.
<body log-click-event>
<div ng-controller="Ctrl">
<button id="button1">button1</button>
<button id="button2">button2</button>
<div id="div1" class="box">
<ul>
<li id="li1">Some LI</li>
<li id="li2">Some LI</li>
<li id="li3">Some LI</li>
</ul>
</div>
<div>