Search code examples
angularjsmean-stackmeanjspageviews

page views functionality in angular js


i have setup mean js on my system. all crud operations work fine. my only issue that i cannot get around is to save pageviews when a user visits a page.

when a user visits a webpage like /articles/:articleId , how to increment the counter of page views for that page

here is my simple view function

$scope.findOne = function () {
  $scope.article = Articles.get({
    articleId: $stateParams.articleId
  });
};

Solution

  • You would need to have a page views field in your mongoose model:

    'use strict';
    
    /**
     * Module dependencies.
     */
    var mongoose = require('mongoose'),
        Schema = mongoose.Schema;
    
    /**
     * Article Schema
    */
    var ArticleSchema = new Schema({
        pageViews: {
            type: Number,
            default: 0
        },
        // other fields
    

    Then add a viewCounter() function to your 'ArticlesController' that increments the $scope.article.pageViews property and updates the article.

    var viewCounter = function () {
      //increment the page views
      $scope.article.pageViews ++
      // update the article record
      $scope.article.$update(function(){
          //handle success
      }, function(err) {
         //handle err
      })
    }
    //call immediately
    viewCounter();