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

Change the x and y positions of several div elements as the mouse moves in JavaScript

I am aiming to create a webpage where multiple divs with text and other content move along the x and y axes of the mouse. The desired effect is similar to parallax scrolling, but I have found that existing parallax plugins are image-based and do not work w ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

"Hover over the image to see it enlarge and reveal text displayed on top using CSS3

I have been working on creating a responsive image page for my website. I've managed to make the images responsive and centered, no matter the size of the browser window. However, I encountered an issue where when I hover over an image, it enlarges a ...

Tips for utilizing ng-model in an Angular application

<input type="search" placeholder="{{'COMPONENT_PROPERTIES.SEARCH_ICON' | translate}}" ng-model="icon.name" list="classIcon" ng-change="changeFn(icon.name)"> <i class="{{$select.selected}}"></i> &nbsp;&nbsp; {{$s ...

Storing video blobs in the filesystem using Electron and Node.js

My electron application allows users to record video from their webcam using the MediaRecorder API. After hitting the "stop record" button, I am able to obtain a blob of the recorded video. I am trying to figure out how to convert this blob into a real w ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

Can an Updatepanel control be added to a webpage using Javascript or JQuery?

I'm currently working on a project that involves allowing users to drag icons representing user controls onto a web page. For the desired functionality, these user controls must be contained within an updatepanel (or a similar AJAX-enabled frame) so ...

Is there a way to incorporate electron methods within Svelte files, specifically in Svelte 3, or is there an alternative approach to achieve this integration?

Currently, I am deep into a project that involves Svelte 3 and Electron 12.0.5 working together harmoniously. For managing hash routing, I have integrated the svelte-spa-router package into my setup. Here is a glimpse of how my project structure appears: n ...

The appearance of all input forms in MaterializeCSS when used in an electron environment appears to

After following the instructions here on how to get started with Materialize CSS, I am having issues with my input form appearing strange: The contents of my current index.html file are as follows: <!DOCTYPE html> <html> <head> & ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

What is the process for retrieving user claims once successfully authenticated on IdentityServer 4?

After setting up IdentityServer4 with angular and WebApi (ASP.NET Core) using this sample: https://github.com/damienbod/AspNet5IdentityServerAngularImplicitFlow, everything is functional. However, I am facing an issue where I am unable to retrieve the us ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

ThymeLeaf does not support the parsing of JavaScript code

I'm working on serving an Angular app with spring boot/thymeleaf. This is the structure of my class that sends html/css/javascript: @Controller public class ResourceProvider { @RequestMapping(method = RequestMethod.GET, value = "/") ...

HTML5: Enhancing Video Playback on the iPad with Custom Zoom Controls

I've customized a smaller UIWebView specifically for the iPad, and I've created my own HTML5 controls for the video playback. However, when I try to maximize the video, all I see is a black screen instead of the actual content. The audio still pl ...

Ensure that all content in the table rows remains visible, even in a table with unusually lengthy cells

My HTML table is structured like this: +-------------+-------------+----------+ | Single line | Single line | Very, | | | | very | | | | long | | | | text, | | ...

Using a function as an argument within an Angular directive

Looking for a solution to pass a promise-returning function into a directive? Here's what I'm currently doing: In the parent controller, I've created a callback: $scope.myCb = function(data) { console.log(data); } Directive Scope: sco ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

How can I organize the selected options from a select2 form element using a basic sorting method?

I am utilizing select2 by ivaynberg and encountering an issue with the data arrangement upon submission. Is there a method to have the results in the form submit data reflect the order in which they were selected in the select2 element, without relying on ...