Saving $routeParam in a variable within a factory service in AngularJS Store

Recently I started working with Angular and now I'm attempting to extract the project ID from the URL and use it as a variable within a service.

Here's my current code snippet:

app.config(
  ['$routeProvider',
    function($routeProvider) {
      ...
      $routeProvider.when('/project/:ProjectId', {
        templateUrl: 'project.html',
        controller: 'ProjectController',
        activePage: 'Portfolio'
      });
      ...
    }
  ])

...

.controller('ProjectController', function($scope, ProjectFactory) {
  $scope.content = ProjectFactory.async();
})

...

.factory('ProjectFactory', function($http) {

  var factoryProject = {
    async: function(page) {
      var projectId = 'XXXXXX';
      var apiKey = 'XXXXXX';
      var url = 'http://behance.net/v2/projects/' + projectId + '?api_key=' + 
                 apiKey + '&callback=JSON_CALLBACK';
      var promise = $http.jsonp(url).error(function(response, status) {
        alert(status);
      }).success(function(response, status) {
        console.log(response.project);
      }).then(function(response, status) {
        return response.data;
      });
      return promise;
    }
  };

  return factoryProject;
});

I feel like I'm overlooking something. How can I store the :ProjectId from $routeProvider into the projectID variable?

Appreciate your help!

Answer №1

In order to make this code snippet work, there are a few key components that need attention. Firstly, it is crucial to include the $routeParams variable within the 'ProjectController' to enable proper functionality.

.controller('ProjectController', function($scope, ProjectFactory, $routeParams) {
    $scope.content = ProjectFactory.async();
})

By incorporating $routeParams into the controller definition, you will be able to access ProjectId via the $routeParams object as follows:

var pid = $routeParams.ProjectId

Subsequently, passing pid as a parameter into the factory can be achieved in the following manner:

ProjectFactory.async(pid)

While I have not yet tested this solution, it appears to encompass all necessary steps for successful implementation.

Answer №2

To utilize the $routParams service in your factory, you must inject it and then retrieve the information as shown below:

var projectId = $routeParams.ProjectId;

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

Guide on displaying a JSON file from a separate port in Symfony2

Just diving into symfony2 and encountering a little challenge here. I've got my localhost all set up using wamp server with some port assignments: Port 80 (default) for symfony: mylocal/app_dev.php/test Port 8080 for the public folder: mylocal:8080/cs ...

I'm experiencing difficulties with JS on my website. Details are provided below – any suggestions on how to resolve this issue

Can someone help me with a web project issue I'm facing? Everything was going smoothly until I tried to add some JS for dynamic functionality. However, when I attempt to access my elements by tag name, ID, or class, they always return null or undefine ...

How to prevent a directory from being copied in webpack within Vue CLI

Currently, I am working on a Vue3 project created using Vue CLI 5.0.1 In my setup, there is a public folder that contains static assets necessary for serving the application. However, this folder is quite heavy, around 1GB in size. Whenever I run the npm ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Need help incorporating a "section trail" into your website's navigation sidebar using JS/jquery? Here's how you can do it!

My website is quite extensive and contains numerous elements. There are times when I find myself wanting to navigate back and forth between different sections of the page. I've noticed that some websites have a feature called a "page trail," which di ...

Tips for transferring a file to PocketBase using NodeJs

Currently, I am in the midst of a project that necessitates uploading numerous PDF files to a PocketBase collection. All the necessary files are saved on my computer and my goal is to upload them using nodejs along with the PocketBase JavaScript SDK. Howe ...

How can I troubleshoot the 'mdDialog console error' that says 'cannot read property element of null'?

Two of my templates are named Left_template_view_html and center_template_view_html When I click on a md-button in the Left_template_view_html I am attempting to display an mdDialog on the document.body What should I pass into the parent parameter: angu ...

Issue with Tanstack React Query failing to import

Attempting to integrate tanstack react query into my current project to handle state management has proven challenging. Following a tutorial on using react query with nextjs 13, I thought I was following it correctly. However, I encountered various import ...

What is the process for converting an <input type="file> into a base64 string?

Currently, I'm attempting to send an image to my express backend by including the image directly in the post request body. var imgValue = document.getElementById("image").value; Within my post request: body : JSON.stringify({ image:imgValue ...

Making an AJAX POST request using jQuery to send the current date and time to an ASP

I am working with an ASP.NET Web API endpoint where I need to send POST data. Suppose I want to post the following information: var myObject = { name: "Alice Johnson", age: "29", accountCreated: "CURRENT DATE TIME" }; What is the JavaScript equivalent o ...

Why is my jQuery clearQueue function malfunctioning?

I'm facing an issue with my AJAX function where multiple notifications are being displayed if the user calls it repeatedly in a short span of time. I want to show the notification only once and avoid queuing them up. AJAX FUNCTION function update(up ...

Evaluating substrings within a separate string using JavaScript

I need to compare two strings to see if one is a substring of the other. Below are the code snippets: var string1 = "www.google.com , www.yahoo.com , www.msn.com, in.news.yahoo.com"; var string2 = "in.news.yahoo.com/huffington-post-removes-sonia-gandh ...

Navigate through the DOM to return an image

I have a question about clicking on the image '.escape' and passing back the source of the image '.myimg2' when clicked. Here is my attempt at accomplishing this task: I understand that it involves traversing the DOM, but I am not very ...

Leveraging Vue.js plugin within a single file component

I am looking to utilize the vue-chartkick plugin in my Vue application, but I want to register it within my single-file components instead of globally. Is there a way to achieve this same functionality without using Vue.use(VueChartkick, { Chartkick })? ...

"Exploring the possibilities of Sketchfab through an AJAX JSON

Currently, I am on a quest to gather the URL for the thumbnail of a Sketchfab model. To access this information, you can visit: Upon visiting the above URL, all the necessary details are visible to me. My next step involves making an AJAX call to dynami ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Does anyone know of a CSS/JavaScript framework that can be used to replicate the look and functionality of the iOS home

I'm wondering if there is a CSS/JavaScript framework that replicates the layout of an iOS home screen. I want to create a kiosk website with a grid layout similar to Android/iOS where apps can be displayed as icons. ...

How can we effectively reroute HTTP requests according to the information stored in a database?

When operating an express server, what is the appropriate method for redirecting incoming requests? In my application, I have two routes: POST and UPDATE. The POST route is responsible for creating a new item in the database, while the UPDATE route increa ...

Transforming RGB Decimal Color to HEX RGB Color in Three.js

Currently, I am facing a challenge in my task involving colors while working with three.js, a JavaScript library. In this particular task, I need to convert decimal color codes (e.g. 12615680) into formats like #FF0000 or 0xFF0000. I am seeking a JavaScr ...

Ways to clear or remove input data in angucomplete-alt

I am having trouble clearing dynamically <angucomplete-alt id="auto-clients" placeholder="Select Client" pause="100" selected-object="vm.curClient" initial-value="vm.client" local-data="vm.clients" search-fields="name" title-field="n ...