Implementing $routeParams in AngularJS service

This task seems simple, but for some reason I can't quite grasp how to go about it.

My goal is to make an API call within a service so that the variables can be accessed by two separate controllers.

The issue I'm facing is the inability to access $routeParams (which is necessary for the GET request) within the service. I'm struggling to understand how to pass $routeParams from the controller to the service.

    app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
    $scope.Page = Page;
}]);

app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
    $scope.Page = Page.posts;
}]);

app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
    var posts = function posts() {
        $http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
            console.log(JSON.stringify(res) );
        }); 
    };
            var description = '';
            var title = '';
            return {
                title: function () { return title; },
                setTitle: function (newTitle) { title = newTitle; },
                description: function () { return description; },
                setDescription: function (newDescription) { description = newDescription; },
                posts
        }; 
}]); 

Answer №1

manufacturing plant :

app.factory('Page', ['$http', function($http) {
        var _posts = function posts(param) {
          return  $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
        };
                var description = '';
                var title = '';
                return {
                    title: function () { return title; },
                    setTitle: function (newTitle) { title = newTitle; },
                    description: function () { return description; },
                    setDescription: function (newDescription) { description = newDescription; },
                    posts : _posts
            }; 
    }]); 

Manager :

app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
    Page.posts($routeParams.slug).then(function success(response) {
       $scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);

please make a note that success is no longer used in the updated Angular versions. It has been replaced with then

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

Deleting table rows after an object has been removed in AngularJSNote: Using

My AngularJS application retrieves a list of JSON objects and displays them in a table. Each row in the table includes a "Delete" button that triggers an ng-click method: <td><a ng-click="testButton()" class="btn btn-danger btn-mini">Delete&l ...

Creating PNG and JPEG image exports in Fabric.js with the help of Node.js

Exploring the wonders of Fabric.JS specifically designed for Node.JS, not intended for web applications, I've successfully created a Static Canvas and added a rectangle to it. Now, it's time to export the image. Take a look at my code snippet bel ...

Endless loop within useEffect causing app to experience performance degradation

I am currently working on retrieving Routes based on a list from firebase realtime db. Below is the code I have: import { onValue, ref } from "firebase/database"; import React, { useEffect, useState } from "react"; import { Route, Route ...

Adjusting the audio playback time with currentTime in HTML5

Recently, I created a HTML5 player that streams music from my server. The player functions flawlessly when playing songs from the beginning. However, when I attempt to play a song from a specific time using the currentTime attribute, nothing happens and th ...

How can I access a separate tab in Woocommerce directly from an icon on the single product page?

I am looking to enhance the functionality of a woocommerce single product page by allowing users to click on an icon below the short description. This will then automatically scroll them down to the tab section and open the corresponding tab. Scrolling do ...

What is the best method for tracking the execution time of functions in Node.js?

My nodejs application has numerous functions that need to be executed. I am looking for a way to log the time taken to execute each function. For example, when my app runs these functions: execfn1(); -> should output in some log, takes: 1ms.. execfn ...

Problem with sending variable via AJAX

Hey everyone, I'm attempting to send form data along with an extra variable using AJAX. Here's the code snippet: function tempFunction(obj) { var data = $('form').serializeArray(); data.push( { no: $(obj).at ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

Display invoices for multiple users logged in at the same time using Express.js

I have recently developed an invoice application using the MERN stack. The app works seamlessly when one user is logged in, but issues arise when multiple users try to access it simultaneously. In such cases, the invoices of the first user remain visible t ...

Sweet Alert seems to be malfunctioning within ajax requests in a Django environment

Experience Soothing Notifications - I’ve incorporated Sweet Alert into my project by using a CDN in the base HTML file: <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> While attempting to utilize Sweet ...

Combining all CSS files into one and consolidating all JavaScript files into a single unified file

Whenever I need to add a new CSS or JS file, I always place it in the header section like this Add CSS files <link rel="stylesheet" href="<?php echo URL; ?>public/css/header.css" /> <link rel="stylesheet" href="<?php echo URL; ?> ...

The continuation of unraveling the mystery of utilizing `overflow-y:scroll` in a horizontal slider

As a beginner, I realized too late that adding code in comments is not an option. Consequently, I decided to create a new question and ask for your assistance once again. To optimize the use of space, I have implemented bxSlider with fixed dimensions (wid ...

Tips for extracting the text either before or after a certain character within a string

Consider the following two strings: var str = "Extract Me @ Leave Me"; var str2 = "Not This @ Yes, This"; Imagine a function named extractString() that can work like this: extractString("frontOf", "@", str); // => Extract Me extractString("behi ...

Instructions on how to extract and display the key-value pairs from a nested JSON array in Angular 2, then populate them in a select box

My goal is to extract data from a Json data model and populate a select box with the data as drop-down items. However, I am encountering difficulties in achieving this as the entire Json array is being printed instead of just the 3 major headings that I wa ...

How to update the state of a component in the root layout from its child components in Next JS 13 with the app router?

I am in the process of upgrading a Next JS app project to utilize the App Router. Within the layout.js (the root layout), there is a Logo component that will be visible on all routes. Within the RootLayout, I am managing a state variable to modify the ap ...

Tips for validating input fields in Ionic to display errors after the user has finished filling them out

*Hello, I'm new to working with AngularJS and I'm currently trying to display an error message after the user has finished typing in the input field. However, I'm encountering an issue where the error message appears as soon as I start typin ...

Unable to receive Ajax response

My current programming setup involves using a combination of JavaScript and PHP to implement an Ajax code. However, at this point in time, the outcome is showing up as undefined. To circumvent this issue, I have resorted to utilizing localStorage to trans ...

Applying Angular to Add a CSS Class

I am working with an Angular controller and have the following model on the scope: $scope.model = { subscriber: { email: '', name: '' }, notice: { text: '', type: '' } } My goal is to display a P tag when notic ...

Generating a new division element with a unique identifier and subsequently making adjustments to it

Just starting out with HTML and JS here, so please excuse my lack of experience and not-so-great English. I have an ID on an HTML element that I want to add content to using a function. Additionally, I need to create another element (inside the first one) ...

AngularJS Cross-Origin Resource Sharing request with a customized header

I'm currently facing issues with enabling CORS on my server while using AngularJS. I am working with Angular version 1.2.16 and below is my server configuration: Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Headers "Cont ...