If someone rapidly clicks on an AngularJS app, the page fails to load

Just a heads up - I am pretty new to Angular. Most of the code is from a tutorial on Lynda that I'm experimenting with. I've noticed an issue when I try to implement a type of "pagination" feature to display various elements from a data.json file. The page fails to load if I quickly click on the anchor links to show the next or previous item. The problem seems to stem from the anchor tags in the details.html file or in the controller of the details. I suspect it might be related to async/await not being utilized properly.

<div class="container">
    <div class="row">
      <div class="col-12 mt-3">
          <div class="card">
            <div class="card-header d-flex align-items-start justify-content-between">
              <h1 class="card-title my-0">{{artists[whichItem].name}}</h1>
              <nav class="btn-group">
                <a class="btn btn-sm btn-secondary" 
                  href="#/details/{{prevItem}}">&lt;</a>
                <a class="btn btn-sm btn-secondary" 
                  href="#/">&bull;Home</a>
                <a class="btn btn-sm btn-secondary" 
                  href="#/details/{{nextItem}}">&gt;</a>
              </nav>
            </div>
            <div class="card-body"
              ng-model="artists">
              <h4 class="card-title text-dark mt-0">{{artists[whichItem].reknown}}</h4>
              <img class="float-left mr-2 rounded"
                ng-src="images/{{artists[whichItem].shortname}}_tn.jpg"
                alt="Photo of {{artists[whichItem].name}}">
              <div class="card-text text-secondary">{{artists[whichItem].bio}}</div>
            </div>
          </div>
      </div>
    </div>
  </div>

To temporarily address this issue, I included the following redirect:

.otherwise({
  redirectTo: '/'
});

I would appreciate any help in understanding the root cause and resolving it. Here's the relevant code snippets below. I have also added console.logs for debugging purposes in my controller without success.

My smaller controller - (controllers.js):

var myControllers = angular.module('myControllers', []);

myControllers.controller('SearchController', function MyController($scope, $http) {
    $scope.sortArtistBy = 'name';
    $http.get('js/data.json').then(
      (response) => $scope.artists = response.data
    );
}); 

myControllers.controller('DetailsController', function MyController($scope, $http, $routeParams) {
  $http.get('js/data.json').then(
    function(response) {
      $scope.artists = response.data
      $scope.whichItem = $routeParams.itemId;

      if($routeParams.itemId > 0){
        $scope.prevItem = Number($routeParams.itemId) - 1;
        console.log("I am going to 18")
      } else {
        console.log("I am going to 20")
        $scope.prevItem = $scope.artists.length - 1;
      }

      if($routeParams.itemId < $scope.artists.length - 1){
        console.log("I am going to 25")
        $scope.nextItem = Number($routeParams.itemId) + 1;
      } else {
        console.log("I am going to 28")
        $scope.nextItem = 0;
      }
    }
  );
}); 

My main app controller (app.js):

var myApp = angular.module('myApp', [
  'ngRoute',
  'myControllers'
]);

myApp.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/', {
      templateUrl: 'js/partials/search.html',
      controller: 'SearchController'
    })
    .when('/details/:itemId', {
      templateUrl: 'js/partials/details.html',
      controller: 'DetailsController'
    })
    .otherwise({
      redirectTo: '/'
    });
}]);

My (index.html) file:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <meta charset="utf-8">
  <title>AngularJS</title>
  <meta name="viewport" content="width=device-width">

  <link rel="stylesheet" href="lib/bootstrap/bootstrap.min.css">
  <link rel="stylesheet" href="css/style.css">

  <script src="lib/angular/angular.min.js"></script>
  <script src="lib/angular/angular-route.min.js"></script>

  <script src="js/app.js"></script>
  <script src="js/controllers.js"></script>
</head>
<body class="bg-secondary">

<div ng-view></div>


<script src="lib/jquery/jquery.min.js"></script>
<script src="lib/bootstrap/popper.min.js"></script>
<script src="lib/bootstrap/bootstrap.min.js"></script>

</body>
</html>

Answer №1

To optimize performance, one recommended strategy is to store data in a dedicated service:

app.service("dataService", function($http) {
    var cache;
    this.get = () => {
        cache = cache || $http.get('js/data.json');
        return cache;
    };
})

In the controller section, implement the following:

app.controller('DetailsController', function MyController($scope, dataService, $routeParams) {
  dataService().then(
    function(response) {
      $scope.artists = response.data
      $scope.whichItem = $routeParams.itemId;
      //...
    }
  );
});

Utilizing this caching method with the $http promise helps prevent redundant requests to the server.

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

The angular bootstrap typeahead feature is experiencing issues when used with a dynamic list that is fetched through the ng

Currently, I am utilizing the typeahead directive in angular-bootstrap. My issue arises when a user changes the input; I aim to trigger an ng-change event to retrieve a list from the server and subsequently filter the results. Once accomplished, I want to ...

Create an Angular-UI function that appends a modal inside a <div> element with the class

We are facing an issue with conflicting rule names between our legacy .css and Twitter Bootstrap on our large website. To resolve this conflict, we have implemented a .sass version of Bootstrap and structured everything as follows: .bootstrap-enabled { / ...

Assign values to several variables when ng-click event is triggered

Is there a smart way to assign values to multiple variables within an ng-click statement in a view without using a controller function? For instance, something like <li ng-click="showLeftDiv = true, showRightDiv = false, showBottomDiv = false"> I ...

Exploring Angular modules has shed light on a certain behavior that has left me puzzled - specifically, when diving into JavaScript code that includes the

I am currently working with angularjs version 1.4.3 and I find myself puzzled by a certain segment of code in the Jasmine Spec Runner that has been generated. Upon generation, Jasmine (using ChutzPath) creates this particular piece of code: (function ...

Preventing Cross-Site Request Forgery in File Upload Submissions

Within my AngularJS application, I have successfully implemented Angular's CSRF protection mechanism for all POST, PUT, and other nonsafe web service calls. However, I encountered a challenge with one specific scenario: performing a multipart/form-dat ...

I am facing an issue with the AngularJS filter not functioning properly with nested JSON key/value objects

Seeking assistance with filtering JSON data based on the code/desc in the state property. Here is an example of my JSON data: $scope.agent = { "0d297c1711de": [{ "applicationName": "rewards-accounts", "agentId": "0d297c1711de", "st ...

What is the best way to horizontally center a div with the layout attribute set to "row"?

I am currently working with a grid composed of cards from the Angular Material library. The issue I am facing is that the cards have a fixed size, which results in extra space on the right immediately after wrapping. My goal is to eliminate this space by ...

Is it possible to access the scope when the Angular-UI-Router is exited?

I'm searching for a potential solution: $stateProvider.state('user', angularAMD.route({ url: '/user/:id', templateUrl: 'views/user.html', controllerUrl: 'views/user', controller: ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...

Issues arise when using the select element

Struggling with submitting my list of items from a select in AngularJS. This is my first time posting here and I'm still finding my way around. The issue lies in using ng-repeat in my HTML to display all items. When the screen loads, it only shows: { ...

Implementing $timeout within the Scope.$watch function allows for monitoring

Hi there, I'm currently working on implementing some functionality in Angular but running into a few issues. I have an ng-model and example-directive configured as follows: <input ng-model="model" type="text" class="form-control"> <div ex ...

The ReactJS form fails to show any updates upon submission

Here is the code snippet I have been working on: const [messages, setMessages] = useState(messagesList); const [addMessage, setAddMessage] = useState({ messageSent: '', }); const addMessageChange = (event) => { event.preventD ...

Commitment without anticipation of a resolution or rejection

While testing one of my AngularJs Services, I decided to write some Unit tests. Below is a sample code snippet that I have come up with: it('', function(done) { aDocument.retrieveServiceFile(extractedFileFeature) .then(function() { ...

How to efficiently import Xlsx and csv files using AngularJS

I am looking for a way to extract data in json format from each line of xlsx and csv files using AngularJS. Currently, I am utilizing the angular-file-upload library to access the file as shown below: $scope.LatLongUploader = new FileUploader({ //url ...

unable to fetch the ID of the checkbox when using the ng-checked directive in AngularJS

My HTML table is populated with data using AngularJs. <tr class="gradeX" ng-repeat="itm in usersList"> <td> <input type="checkbox" ng-checked="itm.checkstatus == 1" ng-mod ...

Enhancing the synchronization of data between the model and the view in

Can AngularJS support "double data-binding" functionality? I am trying to extract mat.Discipline[0].nom_FR from an array containing nom_FR, nom_DE, nom_EN, and nom_IT. The value of mat.Langue[0].langue is either "FR", "DE", "EN", or "IT" based on the sel ...

Single Submit Button with Multistep Form

I'm working on an Angular multi-step form similar to this example. How can I include a save button for each step? Is it feasible to save data separately for each step? For example, when the user is in 'form 1', only save the data from &apos ...

Is Angular Translate susceptible to race conditions when using static files for multi-language support?

Currently utilizing angular translate with the static files loader for implementing multiple languages in my project. However, I've encountered a problem where the loading of language files sometimes takes longer than loading the actual view itself, l ...

Tips for troubleshooting objects within an Angular template in an HTML file

When I'm creating a template, I embed some Angular code within my HTML elements: <button id="btnMainMenu" class="button button-icon fa fa-chevron-left header-icon" ng-if="(!CoursesVm.showcheckboxes || (CoursesVm.tabSelected == 'curren ...

When the Angular UI Bootstrap typeahead ng-model is cleared, it displays as null

The filter is performing admirably, however, after deleting the entered text, the {{filterlist.name}} displays null. This leads to the tables appearing empty due to the presence of null. Check out the demo here: https://plnkr.co/edit/1QVdctw1hr4ggJOtFHUZ? ...