If you're working with any routing system, one approach is to listen for the route change event and then send a request to the server with the route name to update the counter. Here's an example using ui-router.
.run(function($rootScope, PageViews) {
$rootScope.$on('$stateChangeStart', function(e, toState) {
// add a view
PageViews.add(toState.name);
// retrieve the total views for this state from the server
PageViews.get(toState.name).then(function(resp) {
// increment the result by 1 if counting the current view
$rootScope.pageViews = resp.data + 1;
// notify the server that another user has viewed this state
PageViews.add(toState.name);
});
});
})
You have the option to streamline the get/add request so that each trigger updates both the page views and the total count in a single request, if that suits your needs better.
For demonstration purposes, the PageViews
service stores data in localStorage instead of on a server, which would be more appropriate for a production application. http://jsbin.com/fehoxifabo/1/