Angular and Segment.io are both really awesome. One gives you a ton of utilities to get up and running with a single-page app in no time and the other one makes tracking user interaction with that app super easy. If you're not already using Segment.io for your analytics, you're missing out. It adds an abstraction layer to analytics so you just have to add tracking code once and it translates that code into the respective tracking code for all the services you want to integrate. Even better, it works client- and server-side so you have a single interface for all your tracking needs.
I wrote a plugin to wire up these two great services so you can add Segment to your next Angular project with just a couple lines of code.
Just install via bower:
bower install --save ng-segmentio
Add the script tag to your list of scripts:
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/ng-segmentio/build/ng-segmentio.min.js"></script>
</body>
Require it in your app declaration then load the script in a config block. The script returns a promise so you can defer events until after it resolves:
var app = angular.module('app', ['segmentio'])
app.config(function($stateProvider) {
$stateProvider.state('app', {
resolve: {
views: {
header: {
controller: 'headerCtrl',
templateUrl: 'views/header.html'
}
},
analytics: function(segmentio) {
return segmentio.load('YOUR_API_KEY')
}
}
})
})
The above code snippet assumes you're using the fantastically simple and powerful ui-router
for your routing. You can also do something similar but much more tricky using the native $routeProvider
:
app.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'header.html',
controller: 'headerCtrl',
resolve: function ($q, HeaderService) {
var defer = $q.defer()
HeaderService.fetchData(defer)
return defer.promise
}
})
})
That's it! Now segmentio will automatically track pageviews and for custom events you can include it in your controllers like so(using the naming conventions above):
app.controller('headerCtrl', function(analytics) {
$('.expand-button').click(function() {
analytics.track('Clicked the expand button');
});
});
So, get the plugin and star the repo on GitHub if you like it or say hi on twitter!