Retrieve information according to the object ID with AngularJS UI-Router and $stateParams

I have a unique application that directs to a custom URL based on a specific employee ID parameter when an individual employee is clicked in a list. Upon clicking the employee, users are redirected to a detailed employee page with their ID property as a parameter, allowing me to display this property in the DOM.

My goal is to extend this functionality to display all other properties of the employee object in this separate state. While I've explored various solutions, none seem to align with what I'm attempting to achieve.

For instance:

If you click on employee number 21101994 while on the employees/employeesList state, it redirects you to the employees/employeeDetails/?21101994 page and only displays their data in JavaScript fields such as {{employee.firstName}}.

Although I can successfully showcase the ID, my aim is to exhibit ALL the data related to the corresponding employee's ID.

The URL routing functions correctly, directing users from the list page to the details page with the appropriate parameter. However, I struggle to effectively pass the data into the new state or controller.

-

HTML snippet for linking employees:

<li class="collection-item col-xs-12" data-ng-repeat="employee in employees | orderBy: sortByAllDepartments | filter:searchAllDepartments">
    <a ui-sref="employees/employeeDetails({employeeId: employee.id})" class="employeeLink"></a>

-

What I've attempted with the states:

.state('employees/employeesList', {
        url: '/employees/employeesList',
        templateUrl: 'pages/employees/employeesList.html',
        controller: 'employeesListController'
    })

    .state('employees/employeeDetails', {
        url: '/employees/employeeDetails/:employeeId',
        templateUrl: 'pages/employees/employeeDetails.html',
        resolve: {
            employeeId: function($stateParams) {
                return $stateParams.employeeId;
            }
        },
        controller: function(employeeId) {
            console.log(employeeId)
        }
    })

-

Employees service information:

app.service('employeesService', function() {
var employees = [
    {
        id: '21101994',
        firstName: 'Employee',
        lastName: 'One'
    }
];

var addEmployee = function(newObj) {
    employees.push(newObj);
};

var getEmployees = function() {
    return employees;
}

return {
    addEmployee: addEmployee,
    getEmployees: getEmployees
}
})

-

Employees List Controller setup:

app.controller('employeesListController', function($scope, $stateParams, employeesService) {
    $scope.active = 'active';

    $scope.sortByAllDepartments = '+lastName';

    $scope.employees = employeesService.getEmployees();
})

Answer №1

The states will be given parameters such as

 url: '/employees/employeeDetails/{:employeeId}',

Or

url: '',
params: {
  employeeId: null
},
resolve: {...}

I personally prefer the second option for better clarity when receiving.

If you need to store all the employee data, using local storage for the employee object would be more efficient especially if it needs to be accessed frequently or in various parts of the application.

localStorage.setItem('employeeData', JSON.stringify(empData));

To retrieve this data, you can use:

let empData = JSON.parse(localstorage.employeeData); //Object

If you no longer require this stored data, for example, when navigating away from the employeeDetails state, you can delete it using:

localstorage.removeitem('employeeData');

If there is a need to pass multiple state parameters, simply add them as a comma-separated string like:

ui-sref="employeeDetails({id: emp_id, name: emp_name, mobile: emp_mobile})"

And then receive these parameters in the state like so:

params: {
  employeeId: null,
  employeeName: null,
  employeeMobile: null
},

It is advised to limit the number of params being passed in stateParams to avoid confusion and streamline the process.

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

JavaScript Website Struggling to Make Postman REST API Call to Parse Server

I have set up a Parse API Server on Azure and can successfully make REST API calls to it using Postman. However, when I try to replicate this process in my web app using the jQuery AJAX code snippet generated by Postman, I encounter a 400 (bad request) err ...

Is it feasible to save the outcome of a function call using ng-repeat?

Looking for a solution with the following code: <tbody ng-repeat="term in Items | filter:searchText track by term.Element"> <tr class="term-row"> <td ng-show="!IsValid(term)" class="text ...

What is the best way to create a new row at a specific index in an ng-repeat loop?

My Goal: I am aiming to insert a new row of ul after every 2 elements in my ng-repeat loop. For example: <ul class="col-sm-2"> <li><p>Automobile & Motorcycle</p></li> ...

The service did not update the returned variable

I have been following this specific style guide when writing my Angular code: https://github.com/johnpapa/angularjs-styleguide The guide recommends structuring services like this: /* recommended */ function dataService() { var someValue = '&apo ...

Navigating JSON Data in Groovy Using a Loop: A Handy Guide

Just starting out with Groovy and attempting to mock a service in SoapUI. The task at hand involves loading a text file containing JSON data, and then matching that data to a specific node. Here is what I have attempted so far: def inputFile = new File( ...

Using an external function to implement Javascript and AJAX interactions

function makeAjaxRequest(destination_full_url) { if (window.XMLHttpRequest) {// code for modern browsers xmlhttp = new XMLHttpRequest(); } else {// code for old Internet Explorer versions xmlhttp = new ActiveXObject("Microsoft.XMLH ...

Using a directive template to invoke a service method

Imagine you have a custom directive: <product> <img ng-src='{{someImage}}' /> </product> This directive is defined like this: app.directive("product", function() { return { scope: {}, restrict: 'E& ...

Middleware in Express not producing results

Here is the code I am currently using: var express = require('express'); var app = express(); app.use(express.bodyParser()); app.use(express.cookieParser()); var port = Number(process.env.PORT || 5000); app.get('/test/:id', function(r ...

Verification of user input field

For this mini deposit app, I needed to implement validation for the input field to check for three different conditions: no blank entries, only numerical values, and no negative numbers. Despite having the functionality, my attempts at implementing validat ...

The functionality of $viewContentLoading appears to be malfunctioning

Before the content is loaded, I'm attempting to log a value. I am using $viewContentLoading within the init function, but the value is not being logged. Can anyone help me identify the issue with my code? var app = angular.module('plunker&apos ...

Get the file using jQuery ajax post request

Currently, I am attempting to export the data from my web page and download it as an Excel file. However, despite receiving a successful response, the download does not initiate. $.ajax({ type: "POST", url: _url, contentType: 'multi ...

I need to use JavaScript to create HTML to PDF and then upload the PDF file to a SharePoint Document Library

Our current project requires us to convert HTML to PDF and save it in a SharePoint Document Library. While we have successfully converted the HTML to PDF using Kendo plugin, we are facing challenges with storing it in SharePoint. It's worth noting th ...

The input type "number" does not seem to be compatible with the currency pipe feature

The currency pipe seems to not be working when using the input type number. The web page is not displaying any value. I have searched various blogs and it appears that the currency pipe only works with input type text, but my requirement necessitates the ...

Is it possible to implement sticky sessions with Node.js and pm2?

Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

Unexpected JavaScript Bug (with jQuery)

I have an interesting code snippet that captures button clicks and then hides the existing content, revealing the content of the clicked item instead. This code is part of my init.js file along with other functionalities: $(function() { $('#conta ...

Setting up the form.FormController is a simple process that can be

I'm currently in the process of creating a customized input directive. The main objective is to ensure that the form.FormController behaves similarly to other <input> elements with the attribute ng-require="true". .directive('myinput' ...

What is the best way to ensure type safety in a Promise using Typescript?

It seems that Promises in Typescript can be type-unsafe. This simple example demonstrates that the resolve function accepts undefined, while Promise.then infers the argument to be non-undefined: function f() { return new Promise<number>((resolve) ...

"Bringing the power of JavaScript to your WordPress

I have set up a wordpress page and integrated some JavaScript into it. When working in wordpress, there are two tabs on a page where you can input text - 'Visual' and 'Text'. The 'Text' tab is used for adding HTML and scripts ...

How can I ensure that $routeProvider functions correctly within my AngularJS application?

I'm currently in the process of manually constructing a shell and trying to understand its functionality Shell Structure: - application (contains PHP files) - webroot -- app --- app.js -- templates --- main ---- login ----- login.html index.html ...