Strategies for effectively managing dynamic data in Angular service $http requests

I am currently developing an Angular.js application that consumes the public Flickr API. My goal is to create a list/detail view showcasing the most recent photographs from Flickr.

To achieve this, I have implemented a factory in Angular to provide data to two controllers. Below is the code for the factory service:

angular.module('FlickrApp.services', []).
  factory('flickrAPIservice', function($http) {

      var flickrAPI = {};
      flickrAPI.getPhotos = function() {
        return $http({
          method: 'JSONP', 
          url: 'https://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=JSON_CALLBACK'
        });
      }
    return flickrAPI;
  });

Furthermore, here are the implementations of the two controllers (one for the list view and one for the detail view) that utilize the factory service:

angular.module('FlickrApp.controllers', []).
  controller('listController', function($scope, flickrAPIservice) {
    $scope.photosList = [];

    flickrAPIservice.getPhotos().success(function (response) {
        $scope.photosList = response.items;
    });
  }).
  controller('photoController', function($scope, flickrAPIservice) {
    flickrAPIservice.getPhotos().success(function (response) {
        $scope.photosList = response.items;
    });
  });

In my detail view, I have created a link that directs to the detail view based on the position of the photo in the items array. While this functionality works correctly, when the link to the detail view is clicked, the resulting view does not display the correct photo due to the updated list of photos triggered by the second controller using the service.

My desired outcome would be to populate the photosList once from the flickrAPIservice, and have the second controller use the existing data instead of fetching it again each time.

Should I store the photos in a global array? I have been hesitant as I believe this may not align with the 'Angular way' of doing things. Any suggestions or guidance on this matter would be greatly appreciated.

Answer №1

Utilize scope inheritance.

<div ng-controller="parentCtrl">
   <div ng-controller="childOneCtrl"></div>
   <div ng-controller="childTwoCtrl"></div>
</div> 

Save the array on the parent controller's scope like this :

  controller('parentCtrl', function($scope, flickrAPIservice) {
    $scope.photosList = [];

    flickrAPIservice.getPhotos().success(function (response) {
        $scope.photosList = response.items;
    });
  })

Then access it on the child controllers as follows:

  controller('childOneCtrl', function($scope) {
    console.log($scope.photosList);
  }).controller('childTwoCtrl', function($scope) {
    console.log($scope.photosList);
  })

The data will be available and should remain in sync since $digest propagates down to children.

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

Issue with database connection on iOS device seems to be causing trouble

Working on an Ionic Phonegap project for iOS has been a challenge. One specific method in Appdelegate.m caught my attention as it makes an AJAX request to fetch a text file from a server, containing a crucial URL necessary for the app's functionality. ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

When utilizing ASP.NET Core Razor pages for file uploads and utilizing AJAX Post to send the file to an IFormFile handler, the request

I have a straightforward task that involves uploading a file and using AJAX to post it to the Index page: <input type="file" id="file-selector" accept=".txt"> Here is the corresponding Javascript: const fileSelector ...

"Utilize a series of Promise chains within a Promise's then

I am trying to retrieve an array list of object IDs from an API using axios. Once I have the object ID list, I want to fetch the details of each object using promises. This is what I have in mind: var objectDetail = []; axios.get('apiendpoint/&apos ...

Is there a way to turn off the pinch-to-zoom trackpad gesture or disable the Ctrl+wheel zoom function on a webpage

Take a look at this example - While zooming in on the image by pressing ctrl + scroll, the image zooms but the page itself does not scale. Only the image is affected by the zoom. I am attempting to replicate this functionality on my Next.js page. I have ...

Eliminate error messages from multiple input fields within the form by leveraging a directive

Within my form, I have multiple input fields for participant emails: <input name="participant{{$index}}email" type="email" ng-model="participant.email" ng-trim="true" required ng-minlength="1" ng-maxlength="255" ...

Tips for removing "<li>" elements using JavaScript

My issue remains unresolved... I created a tree structure in MVC and added JavaScript code for expanding and collapsing the tree. However, after applying the code, my tree is not being displayed correctly. enter image description here In the image, you c ...

Using Angular to make GET requests with JSON data in PHP

Seeking assistance with connecting Angular frontend to PHP backend. Upon calling the service, I am receiving an empty array in the console. Controller: angular.module('pageModule') .controller('pageController', ['$scope', &a ...

Ensuring validity with Vuelidate for customizable fields

There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same ...

What are some effective methods for retrieving data through an ajax request?

Incorporating ajax into my javascript code has presented a challenge. $('#btnCart').click(function() { var pName = document.getElementById('prodName').value; $.ajax({ url: 'index.php', data: 'prd ...

What should you do if the Optional Parameter concept is not functioning as expected?

I need to modify a JavaScript function that retrieves a value from a textbox depending on the selected Radio button. For example: If the Radio button No is selected, the value is retrieved from TextBox A. However, if the Radio button Yes is selected, the ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...

Having trouble with AngularJS WebApi Put request not working properly?

I have encountered this issue before and despite my attempts to resolve it on my own, I have been unsuccessful. Here is the code snippet that is causing me trouble: ... $resource("/SWDB/api/admin/users/:id", { id: "@id" }, { update: { ...

Guide on navigating an array of objects using the provided keys as a starting point in Javascript/Typescript

Assuming I have an array of objects structured like this: const events: Array<{year: number, month: number, date: number}> = [ {year: 2020, month: 10, date: 13}, {year: 2021: month: 3, date: 12}, {year: 2021: month: 9, date: 6}, {year: 2021: mont ...

How can I retrieve data using the angular method instead of the traditional $.ajax approach? Is $http a suitable replacement for $.ajax in Angular?

Here is the code snippet I have written. .state("dynamic", { url: "/:name", controller : 'AppHomeCtrl', templateUrl: function (params){ var myURL = params.name + '.html'; var validPage ...

Unexpected Memory Drain in Ionic and Cordova on iOS

I've encountered an unusual memory leak in my Ionic and Cordova application. This leak is not present when running the app in Chrome, but it clearly appears when I test the app. The issue arises when I need to iterate through a large data set and assi ...

Angular ng-click event for dropdown selection in Ionic

I've implemented a select input positioned over a musical time signature using CSS with a low opacity to keep it hidden. On clicking the time signature, the user inadvertently clicks the select input, which reveals the options. Yet, I'm struggl ...

AngularJS - Embedding input fields within an HTML table within a form

The system is up and running now... I retrieve an array and insert the name into an input field. Then, I update the name in the input field and send it back using a PUT request. Here is the HTML code: <form id="edit"> <table> < ...

Obtain the currently selected HTML element using tinyMCE

Within my editor, I have the ability to choose text and show it using the code below: alert(tinyMCE.activeEditor.selection.getContent({format : "html"})); The problem is that this function only returns text and not HtmlElement. This means I am unable to ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...