The stateParms phenomenon

I have encountered an issue regarding $stateParams that I am trying to comprehend:

The code I am using to navigate through states is as follows: In my controller:

$scope.goToPath = function ( path, pid ) {


    $scope.pid = pid;
    console.log("Current scope pid : " + $scope.pid + ", Full path : " + $state.current.name);
    $state.go(path, {projectId : pid} );
};

In the state definition:

state('projects.detail', {
             url: '/detail',
             params : { projectId : null},
             templateUrl: 'app/pages/projects/detail/detailProject.html',
             title: 'Detail of the project',
        });

Then I am invoking this function using ng-init:

$scope.getProjectById = function () {

    projectFactory.getProject($stateParams.projectId)
        .success(function (data) {
            if(data == null){
                $scope.errorMessage = "The project with id : " + pid + " does not exist";
            } else {

                $scope.project = data;
                $scope.project.startDate =  new Date(data.startDate);
                $scope.project.endDate =  new Date(data.endDate);
            }
        })
        .error(function (data, status, headers, config) {
            $scope.errorMessage = "Error 1: " + data.error + ' ' + status;
        });
};

As evidenced here, I am passing $stateParams.projectId which corresponds to the value defined in my state.

In my factory, I have the following code:

 factory.getProject = function (projectId) {
    console.log('Project Id from factory: '+ projectId + $stateParams.projectId);
    return $http.get('http://localhost:8080/projectmanagement/Project/' + $stateParams.projectId)
};

However, when I execute this code, I am getting projectId = undefined AND $stateParams.projectId = 4. Since I am passing the projectId in the function, it should ideally have a value, right? Can someone help explain this discrepancy? Your assistance would be greatly appreciated. Thank you.

Answer №1

For me, the issue lies in the design:

Imagine this as the HTML structure of your application:

<div ng-app="demoApp" ng-controller="appCtrl">
    <a href ng-click="goToPath('detail', 456)">redirect</a>
    <div ui-view>
    </div>
</div>

You have a controller within your app to handle redirection. When passing /detail to the $state.go function, remember that it requires the state's name, not the URL.

The second function, triggered by ng-init in the state's template, should ideally be declared in the state's specific controller:

angular.module('demoApp', ['ui.router'])
  .controller('appCtrl', function($scope, $stateParams, $state){
        $scope.goToPath = function ( path, cid ) {
        alert(path + ' ' + cid);
        $scope.cid = cid;
      $state.go(path, {clientId : cid} );
    };
  })
    .config(routes);

function routes($urlRouterProvider, $stateProvider) {

    $urlRouterProvider.otherwise('/');

    $stateProvider
        .state('detail', {
            url: '/detail',
             params : { clientId : null},
             template: '<div ng-init="getClientById()">ok</div>',
             title: 'Client Details',
             controllerAs: 'detail',
             controller: function($scope, $stateParams){
               $scope.getClientById = function () {
                 alert($stateParams.clientId)
               } 
              }
        });
}

Check out the solution on JSFiddle here.

With this revised code, you can retrieve the client's ID and pass it to your service 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

What is the best way to create dynamic .env files that can easily adapt to different environments instead of

Having multiple .env files (one for Vue and one for Laravel) with 'localhost' hard coded in them is causing accessibility issues from other computers on my network. It would be beneficial to have this set up dynamically, except for production. F ...

Execute CSS within jQuery code only when the body class is present

I am attempting to use CSS (display: none;) within a script to hide elements from my menu only if a specific language is active. When the body class changes from one language to another, I want the script to check if the body class of a certain language ...

Modifying webpage code

I am looking to develop a system where I can edit various elements such as the navbar, paragraphs, and images directly from a web page. I understand that this can be achieved with JavaScript, but I am facing the issue of my customizations reverting to defa ...

Numerous operations included in a JavaScript document

Looking to enhance my JS file by adding multiple functions, but I'm having trouble as I'm not very familiar with JavaScript. Here's what I've got so far. $(function(){ $('.incentives').hide(); $('.incentives-click&a ...

Ways to display encoded URL image using <img src>

I have a scenario where I am dealing with a URL of an image link location that does not have a file extension like .jpg, but when accessed it displays the corresponding image. How can I output this URL in PHP? For instance, take the example of the reCAPTC ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

Using Typescript to establish a connection between ngModel and an object's property

Let's talk about how we can dynamically bind an input to an undefined property in an object. For example, we have an object named user: let user = {}; How can we bind an input to a property that doesn't exist yet? Like this: <input [(ngMode ...

Catalog indexed in a JSON document

I'm currently facing an issue with extracting data from a JSON file and populating a list with that information. HTML : <ol id="dataT"> </ol> JavaScript : function GetData(index) { var xhttp = new XMLHttpRequest(); xhttp.onre ...

Enclose Angular $resource requests that do not return POST data

Currently, I am working on enhancing my $resource requests by implementing a straightforward wrapper. The primary objective is to incorporate some logic before the request is actually sent. For guidance, I referred to an informative article authored by Nil ...

What is the best way to retrieve the name of an element or component using JavaScript

I'm currently working on a webpage that includes ASP.NET panels and JavaScript which retrieves all components present on the page: var items = Sys.Application.getComponents(); My goal is to obtain the name/ID of each element stored in the 'item ...

Discover the secret to opening two JPG files on YouTube using just one URL!

I was curious about the way YouTube thumbnails function. Here is an example thumbnail from a random YouTube video. There is an hqdefault.jpg in the URL, followed by some variables that indicate the size. If we remove or change these variables, a larger im ...

JavaScript's asynchronous callbacks

As a PHP developer delving into the world of NodeJS, I find myself struggling to fully grasp the concept of asynchrony in JavaScript/Node. Consider this example with ExpressJS: router.get('/:id', function (req, res, next) { var id = req.par ...

Unable to determine why node.js express path is not working

const express = require("express"); const app = express(); app.use(express.static("public")); var dirname = __dirname; app.get("/:lang/:app",function(req,res){ console.log(req.params.lang + " " + req.params.app); ...

How to Implement Click Actions on Elements in AngularJS

Just starting out with angularjs and I have a scenario with jQuery. handleClick(); function handleClick() { var doubleClick = false; $('#text span.word').on('click', function() { var that = this; setTimeout(funct ...

Data Binding in AngularJS appears to be non-functional

Experimenting with AngularJS, I created a small code snippet that doesn't seem to bind data properly. Here is the HTML and JS code for those who prefer not to visit the provided link: first.html <!doctype html> <html ng-app="firstApp"> & ...

Arrows within modal image (adjusting size based on image)

In my modal carousel, the position of the arrows changes based on the image resolution. I would like the arrows to always remain inside each image, regardless of resolution. ...

AngularJS: Step-by-step guide to setting up routing in each module

What is the optimal method for configuring routing in each module? ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...

How to present MongoDB data on the frontend using Node.js without relying on a framework

As someone with experience in HTML, CSS, and JavaScript, I am new to Node.js and server-side programming. Although I can serve HTML pages using FileSystem and the request.url stream in NodeJS, I need assistance as I navigate through my first server-side la ...