Track the amount of views on an AngularJS page and display the total count

Looking to add a view count feature to my website using angularjs.

Similar to stackoverflow's question view counter, I want it to be persisted.

I'm considering intercepting the http request, updating the backend asynchronously, and then updating the data locally (maybe using cookies or localStorage).

Does anyone know how this can be done?

Thank you in advance

Answer №1

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/

Answer №2

In my opinion, a good approach would be to have the backend display the pageview number in the response, with that number incrementing each time by updating the database. However, if you prefer to use an async API call for this purpose, here is a workaround suggestion:

You could intercept every anchor click and initiate an async call before allowing the link redirection (shown here using jQuery):

$(window).click(function(event){

   if(event.target.is('a[href]')){

    yourAsyncFunction();
    window.location.href = $(event.target).attr('href'); // Use this line if you wish
                                                         // to proceed to the destination
                                                         // of the clicked anchor
   }

   return false;     

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using Javascript to append content to the body, it may not be displayed as HTML on

My current project involves creating an HTML document through JavaScript templates. In the code snippet below, I have a const button which serves as my template. By using the replace method, I am able to update the content within the button template from c ...

Issue: encountered an ECONNRESET error when attempting to read using the request module in mode.js

When attempting to download and parse large XML files from affiliate sites without a proper API, I encounter the same error consistently while using the request module for Node.js. Error: read ECONNRESET at exports._errnoException (util.js:746:11) at TCP. ...

Refreshingly modernizing SVG in Angular

I've been facing a challenge in my Angular application where I am trying to dynamically add paths to an SVG element within an HTML file. The issue is that even though the paths are getting added to the DOM, they are not showing up in the browser when ...

Adding an onload event in a function-based component without using a fetch call

Looking at the code snippet below for a React component: import React from "react"; import { Carousel } from "react-bootstrap"; function CarouselHome() { return ( <> ...

Adding JQuery to a running webpage using the DOM and Opera browser add-ons

I'm currently working on an Opera Extension and I have a question. Is there a way to use the includes folder in order to directly inject jQuery into the live HTML of a webpage? For example, can I change the background color of the DOM to black? If ...

Jquery and adaptability

I currently have a scrollTo anchor link script on my website that has an offset of -35px to account for my 35px high navigation bar. However, I find that this offset may need to be adjusted for different screen resolutions, such as smartphones or tablets ...

Adding ttf files to the content script of a Chrome extension

Currently, I am using a content script to inject some HTML into a webpage. My goal is to incorporate the google font named CabinCondensed-Regular, along with several icon fonts that I obtained from IcoMoon. I have already downloaded the necessary font file ...

Troubleshooting Problem with AngularJS and canvasJS

I'm facing some challenges while creating a basic website with angularJS that involves dynamic charts based on selected data. I encountered errors when trying to integrate canvasJS into my project. Despite studying examples on how to use canvasJS, I a ...

Leveraging JavaScript functions within an HTML file on an Android device

Currently, I am facing an issue with loading and playing videos via streaming in my Android app using a JavaScript code inside an HTML file. My approach involves using a WebView to showcase the video content. However, the challenge lies in the fact that th ...

Exploring the interactive doughnut graph using SVG and Vue.js

Looking to create a unique dynamic donut chart using SVG and Vue. I want it to mirror the exact SVG format found on this webpage: (To see the animated chart, select a dish and click on ingredients) This might not have been the best approach, but it was ...

Boundaries on Maps: A guide to verifying addresses within a boundary

User provides address on the website. If the address falls within the defined boundary, it is marked as "Eligible". If outside the boundary, labeled as "Ineligible". Are there any existing widgets or code snippets available to achieve this functio ...

Adjust the background color dynamically as you scroll, given that I am using a linear-gradient

Is it possible to change the color background using JavaScript while scrolling, especially if I have a linear gradient like this: background: linear-gradient(115deg, #42c344 0%,#42c344 40%,#c4efc4 40%,#ffffff 40%,#ffffff 100%); background-attachment: fi ...

Selector that targets an attribute in the beginning of its value [name^=value]

When trying to match input fields by name, I encountered a challenge. The names consist of a base name plus square brackets, which the PHP interpreter converts into arrays. According to the jQuery API, the suggested selector is as follows: ":input[name^=f ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

The incorrect value of variable V is being passed to the doSomethingWithData(v) function. This could lead to unexpected results

const Greetings = () => { const [num, setNum] = React.useState(1); React.useEffect(() => { setTimeout(async () => { await setNum(2); processData(num) }, 3000) }, []); retur ...

ERESOLVE encountered difficulty resolving the error during the execution of npm install

I've been struggling with resolving dependency conflicts while installing and updating npm packages. The error message in the console is provided below. I have attempted to install legacy dependencies and re-install some modules, but nothing seems to ...

Preserve the model's key and value in the scope without saving it, thereby avoiding duplicating input fields

This is my data model: { aktuell: { N5: '8', Auftragsnr: 123 }, historie: [ { some data }, { more data } ] }; Below is the HTML code I am using: <ul> <li> <span ng-repeat="(key, value) in friends[0].akt ...

Instead of relying on traditional AJAX for receiving remote commands, consider using a new Image object in your code like this: `var

How efficient is the following method: var i = new Image(); i.src = 'http://secondary.domain.com/command.gif?command=somecmd&rand=' + ...epoch time....; ... utilizing mod_rewrite to redirect the above URL to a PHP script ... Is this an effe ...