Navigating through certain JSON information in AngularJS

I am facing a challenge with handling article information stored in a json file, where each article has a unique id. The format of the json data is as follows:

[{"title":"ISIS No. 2 killed in US special ops raid",
      "id":"14589192090024090",
      "agency":"foxnews",
      "text":"Article text goes here.",
      "topic":"Politics",
      "imagePath":"resources\/images\/foxnews\/14589192090024090.img.jpg"},
     {"title":", etc etc }]
    

On my main page, I have a list view that displays the title and author of each article. When a user clicks on an article, I want to show detailed information such as the text, topic, etc. In order to retrieve the json data, I utilize the following AngularJS factory:

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

      trooNewsServices.factory('Articles', ['$resource',
      function($resource){
        return $resource('resources/articles.json');
      }]);
    

To access the full list of articles in my home page controller, I use the following code:

this.articles = Articles.query();
    

My current struggle lies in displaying the selected article's information on the next page. I aim to achieve this by retrieving the specific id using $routeParams.id and then locating the corresponding article in the json data. Below is a snippet from my selected article controller:

TrooNews.controller('ArticleController', ['$routeParams','Articles',
        function($routeParams, Articles) {

            //look through articles for specific article using routeparams
            Articles.query().$promise.then(function(articles) {

                for(i = 0; i < articles.length; i++){

                    if(articles[i].id===$routeParams.id){
                        this.selectedArticle=articles[i];
                    }

                }

            });

            console.log(selectedArticle);
    }]);
    

However, I encounter an error stating 'Could not instantiate controller ArticleController'. Is there a way to access the selectedArticle variable outside the promise function?

Answer №1

RevolutionNews.controller('PostController', ['$routeParams','Posts',
    function($routeParams, Posts) {
       var controller = this;
       controller.selectedPost = null;
       controller.setSelectedPost = function(post){
          controller.selectedPost = post;
       }
       //search for specific post using route parameters
       Posts.query().$promise.then(function(posts) {
          for(j = 0; j < posts.length; j++){
            if(posts[j].id===$routeParams.id){
                controller.setSelectedPost(posts[j])
                break;
            }
        }
    }); 
}]);

Answer №2

When making an asynchronous call, it's important to remember that the results may not be available immediately after the call. You can use a callback method like this:

Articles.query().then(function(allArticles){

    for(let i = 0; i < allArticles.length; i++){
        if(allArticles[i].id === id){
            selectedArticle = allArticles[i];
        }
    }

    console.log(selectedArticle);
})

Alternatively, you can trigger a scope digest within the callback itself.

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 issue I am facing is that the angular chart.js is not resizing properly when placed within a flex

Take a look at the fiddle below: https://jsfiddle.net/m942h0wm/6/ Here is the HTML code: <div class="container" ng-app="app"> <div class="main"> <p>Main</p> </div> <div class="aside"> <canvas class="c ...

The function 'createUser' is not a valid method in AngularFireAuth

Recently, I've been delving into AngularFire .5 and Firebase after installing them using Bower Install. To start off, I browsed through the code base of Firereader on GitHub and have been working on updating the methods. Everything seems to be loadin ...

The behavior of $parent.$index differs between ng-bind and the DOM environment

I am facing an issue where I need to generate a scope variable dynamically based on the indexes from 2 nested ng-repeat directives. The expression works fine when displayed in the DOM, but it does not work inside ng-bind (specifically $parent.$index). Here ...

Leveraging Webpack and Jest for seamless module importing in a development project

I've been working on a Node project and utilizing imports and exports extensively. To package the frontend code, I opted for Webpack. However, it seems to require running as common JS. Moreover, Jest is being used in my project, which led me to spec ...

Is there a way to refresh a PHP file using Ajax?

So I have this PHP file that generates a .txt file containing the names of some photos. The thing is, new photos are constantly being added to the images folder. To address this issue, I've set up a JavaScript function on my index page that calls an A ...

Utilizing material-ui's LocalizationProvider to display times in a different time zone

My application requires material-ui date and time pickers to function based on a remote time zone specified by the server. I want the today circle on the date picker to accurately reflect today in the remote time zone, and I need to convert the datetimes i ...

The onClick action kicks in as soon as the page finishes loading

One particular line of code in the Button Tag has caught my attention. let content = this.props.searchResult.map((ele, i) => { let card_id = ele.user.username + "_card"; return( <div className="col s12 m6 l4" key={i} id={card_id}> ...

With Crypto-JS, a fresh hash is always generated

I'm looking to integrate crypto-js into my Angular 8 application. Here is a snippet of my code: import {Injectable} from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Injectable() export class HprotoService { public ...

What is the best way to invoke a controller function from within a directive's link function using '&' and passing a parameter?

Trying to pass a parameter into a function within a directive link function has been a bit challenging. I've come across questions and examples like this one on Stack Overflow, as well as blog posts such as What IBroke. While I've seen paramete ...

What is the process for excluding a file from running in jest?

Currently, I am working on integration tests using Jest and I have a folder with 20 test files. However, there are three specific files in that folder that should not be executed during the testing process. I tried using testPathIgnorePatterns, but it seem ...

The Angularfire library encountered an issue when trying to access the 'push' property of a null object

I am currently in the process of creating a new object in the database for an assessment. Right now, I have hardcoded it to test its functionality, but ultimately, it will be dynamic based on user input from the view. However, I am encountering an error th ...

Is it possible to clear a div using jQuery and then restore its contents?

In my setup, I have a video player within a div where clicking the play button (.video-play-container) fades in the video, and clicking the close button (.close-video) fades it out. The issue arose when the faded-out video continued playing in the backgr ...

The RemoveEventListener function seems to be malfunctioning within Angular2 when implemented with TypeScript

I am currently incorporating three.js into Angular2. The code I am using is quite straightforward, as shown below. this.webGLRenderer.domElement.addEventListener('mousedown', ()=>this.onMouseDown(<MouseEvent>event), false); this.webGLR ...

Preventing circular dependencies while upholding the structure of modules in Express

I am developing an express app in ES6 and organizing my files by functionality. In this structure, each module has an index.js file that is responsible for exporting relevant methods, classes, etc. Other modules simply require the index.js from another mod ...

Is there a way to customize the ::selection style using mui createTheme?

I'm looking to globally change the color and background color of ::selection in my app. Can anyone advise on how to achieve this using createTheme()? ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

Determining when a message has been ignored using php

One of the features I am working on for my app is adding announcements, which are essentially personalized messages to users. Once a user receives a message and dismisses it, I want to ensure that specific message does not appear again. Here is the PHP co ...

Modifications made to the process module in one file are not reflected in a different file

It seems that the process module in NodeJS is not global, resulting in changes made to it in one module not reflecting in other modules. To confirm my findings, I wrote a small piece of code. Here is the snippet: server.js import app from "./app.js& ...

Assistance with JSONP (Without the use of jQuery)

I've been putting in a lot of effort trying to understand how to make a JSONP request, but all the reference materials I find are full of jQuery examples. I can go through the jQuery source code, but I prefer a straightforward and simple example. I&ap ...

Utilizing the JSON.parse method in JavaScript in conjunction with an Ajax request while incorporating the escape character "\n" for new line functionality

https://jsbin.com/zuhatujoqo/1/edit?js,console Edit: json file has this line: {"pd":"ciao \\n ste"} I need to retrieve a valid JSON file through an ajax call. Then parse the result using JSON.parse. I'm confused about the behavior of t ...