What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet.

app.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        templateUrl: "partials/home.html",
        controller: "mainController",
    })
    .when('/products', {
        templateUrl: "partials/productlist.html",
        //controller: "ProductController",
    })
    .when('/product/:prodID', {
        templateUrl: "partials/product.html",
        controller: "viewController",
    })
    .when('/contact', {
        templateUrl: "partials/contact.html",
        controller: "contactController",
    })
    .otherwise({
        redirectTo: "/"
    });
});

app.controller('ProductController', function($scope, $http){
    $http.get('partials/productTable.json').success(function(response){
        $scope.datap = response.lists;
    });
 }).
controller('viewController',function($scope,$routeParams){
    $scope.eachproduct = $scope.datap[$routeParams.prodID];
});

In my product.html page's code, you'll find:

<div ng-controller="viewController">
    <ol class="breadcrumb">
        <li><a href="#">Home</a></li>
        <li><a href="#">Products</a></li>
        <li class="active">{{eachproduct.link}}</li>
    </ol>
    <div class="col-md-4">
        <figure><img ng-src="{{ }}"></figure>
        <p>
            <a href="">Read More</a>
        </p>
    </div>
</div>

However, there seems to be a problem as the value of {{eachproduct.link}} doesn't display when navigating to any product page.

If anyone has a solution for this issue, I would greatly appreciate it. Thank you!

Answer №1

Opt for $rootScope over $scope

$rootScope

The $rootScope serves as the highest-level scope within an application. It is a single entity that is accessible across all components of the app, functioning like a global variable. All other $scopes are descendants of the $rootScope.

Example :

    controller('viewController',['$scope','$routeParams', '$http','$rootScope',function($scope,$routeParams, $http,$rootScope){
    $http.get('partials/productTable.json').success(function(response){
        $scope.datap = response.lists;
       $rootScope.eachproduct = $scope.datap[$routeParams.prodID];
     });
   }]);

Answer №2

app.controller('ProductController', function($scope, $http){
    $http.get('products.json').success(function(response){
        $scope.data = response.items;
    });
 }).
controller('ItemViewController',function($scope,$routeParams, $http){
    $http.get('products.json').success(function(response){
        $scope.data = response.items;
        $scope.selectedItem = $scope.data[$routeParams.itemID];
    });
});

Answer №3

If you're in need of an Angular provider, such as a factory, to store and pass values between controllers when using routes, consider the following example:

While the provided example doesn't incorporate routes, the concept remains consistent. Check it out here: https://jsbin.com/wiwejapiku/edit?html,js,output

To delve deeper into providers, visit this link: https://docs.angularjs.org/guide/providers

Your specific implementation might resemble something like this:

app
.factory('productFactory',function(){
    return {
        data: {}
    };
})
.controller('ProductController', function($scope, $http, productFactory){
    $scope.productFactory = productFactory;
    $http.get('partials/productTable.json').success(function(response){
         $scope.productFactory.data = response.lists;
    });
}).
controller('viewController',function($scope,$routeParams, productFactory){
    $scope.productFactory = productFactory;
    $scope.eachproduct = $scope.productFactory.data[$routeParams.prodID];
});

Keep in mind that you'll also need to update your view to reference 'productFactory.data' accordingly.

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

Encountered an unexpected character in C# Json.net during value parsing: [

public class JSON_Explore_Root { public string browse_content { get; set; } public List<JSON_Browse_Content> Content { get; set; } } public class JSON_Browse_Content { public string link { get; set; } public string image { get; set; ...

Is there a way to efficiently import multiple Vue plugins in a loop without the need to manually type out each file individually?

I am looking for a way to streamline this code by using a loop to dynamically import all .js files from a specified directory (in this case, the 'plugins' directory). const plugins = ['AlertPlugin', 'AxiosPlugin', 'Confi ...

What is the reason that property spreading is effective within Grid components but not in FormControl components?

Explore the sandbox environment here: https://codesandbox.io/s/agitated-ardinghelli-fnoj15?file=/src/temp4.tsx:0-1206. import { FormControl, FormControlProps, Grid, GridProps } from "@mui/material"; interface ICustomControlProps { gridProps?: ...

Delaying consecutive calls to query on mouse enter event in React

Currently, I have a React component from antd that utilizes the onMouseEnter prop to make an API query. The issue arises when users hover over the component multiple times in quick succession, which floods the network with unnecessary API calls. To prevent ...

Previewing multiple images with multiple file inputs

I am trying to find a way to preview multiple images uploaded from different inputs. When the button is pressed, the content from a textarea containing <img src="$img" id="img1"> is written inside a div called seeimg. The IDs for these images range f ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

Retrieving data via AJAX from an SD card

I am using the Atmel SAM4E-EK microcontroller as a server to host a webpage and send data over HTTP protocol. I am currently facing an issue with the download function while trying to download a file from my sd_card, which will not be larger than 512MB. s ...

The ng-model remains unchanged when the <select> element is modified using JavaScript

I am currently working on creating a customized dropdown box with the help of JavaScript and anglersJS to connect the data with the select element. The user interaction involves clicking on a div element that is styled to act as the dropdown option. This d ...

Tips on including variables within quotation marks in JavaScript

I'm currently working on a JavaScript project using Pug. My goal is to use Express and MongoDB to develop a CRUD application that generates an edit button for each post, triggering a specific event when clicked. However, instead of the desired resul ...

Having trouble interacting with Xpath elements using Selenium and Java?

I have been attempting to access a search bar and submit the query without a SEARCH BUTTON. While I was able to enter the search query using javascriptexecutor, I encountered difficulty when trying to perform an Enter button action as there was no actual E ...

What's the best way to align divs vertically in a compact layout?

Update The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content ...

Switch between playing and pausing the mp3 audio in the Next application by using the toggle

I am currently working on my website and I have been trying to add a button to the bottom of the page that can play or pause a song using useSound library. The song starts playing when I click it for the first time, however, I am facing difficulty in stopp ...

Utilize JavaScript to send login information to a website

I have a specific task in mind: creating a script that will automatically fill in certain data on an HTML website. To illustrate, let's imagine the site is the StackOverflow login page and I want to input my username and password. For the username fi ...

Attempting to create a dynamic dropdown menu with animated effects triggered by a key press

I've been attempting to construct a menu that initially appears as a small icon in the corner. Upon pressing a key (currently set to click), the checkbox is activated, initiating the animation. Most of the menu and animation are functional at this po ...

Modify the heading color of elements in a class to a distinct color when the cursor hovers over the element

I currently have 3 heading elements: elem1, elem2, and elem3. When I hover over elem1, I want elem1 to turn yellow and elem2 and elem3 to turn purple. If I hover over elem2, I want elem2 to be yellow and the others to be purple. Once I release the hover, I ...

Ways to transform an ISO string formatted date time into the following hour

I have a function that converts my date to RFC3339 format, but I want it to be converted to the upper time limit. Could someone please help me figure out how to convert it to the upper limit? const date = new Date(); // converting to RFC 3339 format ...

Need help speeding up website load times?

My website is loading incredibly slow, even though it has minimal content. I suspect that the high number of images and JavaScript elements on the page are contributing to this issue. Is there a method available to diagnose what exactly is causing the ext ...

Analyzing latency in node.js through numerous requests

Is there a way to send multiple requests in a loop, and measure the time of each request? In PHP I'd do: require 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client(); for ($i = 0; $i < 100; $i++) { $start = mic ...

Mongoose is encountering issues with error handling due to the 'useUnifiedTopology: true' pass option

Recently, I discovered that by using the 'useUnifiedTopology: true' option in Mongoose, it eliminates the emission of an error if there are issues with the connection. For instance: mongoose.connect(DB, { useNewUrlParser: true, useCreateInde ...

Can you extract debugging details from an ajax preflight inquiry?

I am currently working on a JavaScript project that involves making an AJAX request. However, I am encountering issues with the preflight OPTIONS call for this request failing. To provide some transparency to the user, I would like to display debug infor ...