Retrieve data from server using Angular and present content on a dedicated webpage

I am currently working on a page that displays all usernames, and when I click on a username, I want to retrieve more information from the server and display it on a separate User page (including first name, last name, etc).

However, I am encountering an issue where the fields are not populated when I click on a username. Can someone please review my code and advise on what might be going wrong?

app.config(function($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl : "pages/login_page.html"
        })
        .when("/userpage", {
            controller : 'UserController',
            templateUrl : "pages/user_page.html"
        })
        .when("/allusers", {
            controller : 'AllUserController',
            templateUrl : "pages/all_users.html"
        });
});

This is my login code. After a user is authenticated, they can view all other users by changing the view to #allusers.

app.directive("loginForm", function (AuthorizedHttp, ConfigurationRepository, UserObj) {
        return {
            restrict: 'E',
            scope: {
            },
            templateUrl: 'templates/login-template.html',
            replace: 'true',
            controller: ['$scope', '$http', '$window',
                function($scope, $location, $window) {
                    $scope.loginError = false;
                    $scope.login = function () {
                        // Code for logging in
                    }
                }
            ]
        }
    });

The following code is responsible for retrieving all users and works correctly.

app.controller('AllUserController', function ($scope, AuthorizedHttp, ConfigurationRepository, UserObj, UserCurrent, TimezoneService) {

    $scope.init = function () {
        // Code for initializing
    };

});

Here's the HTML that displays all usernames and allows users to click on them to retrieve necessary information:

<div ng-controller="AllUserController"  ng-init="init()">
    <div ng-controller="UserController">
        <div ng-repeat="email in users_emails" class="item-unchecked">
            <a ng-click="getUser(email)">{{email}}</a>
        </div>
    </div>
</div>

The User controller is executed every time a username link is clicked:

app.controller('UserController', function ($scope, AuthorizedHttp, ConfigurationRepository, UserObj, UserCurrent, TimezoneService,  $window) {
$scope.user_display_name = 'Not set yet';

$scope.getUser = function(username) {
    // Code for getting user data
};

});

Despite setting the scope values before changing the $window.location, the user_page.html loads without all fields being set. Any insights on why this might be happening?

Answer №1

  1. Eliminate the ng-controller="UserController" from your HTML code.
  2. In your AllUserController, create a new function like this:
    
    $scope.customNavigate = function(routeToNavigate, routeParameter){
           $location.path("/" + routeToNavigate + "/" + routeParameter);
        }
  3. Modify .when("/userpage", { to .when("/userpage/:email", {
  4. Replace ng-click="getUser(email)" with

    ng-click="customNavigate("userpage", email)"

  5. Add $routeParams to your UserController dependencies

  6. Change
    $scope.getUser = function(username) {
    to function getUser (username) {
  7. Invoke getUser($routeParams.email) in your UserController.

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

Determine the quantity of items currently in an active state

I created a function that toggles the active state of list items when clicked: React toggleActive: function(item){ item.active = !item.active; }, JSX <li key={property.id} onClick={() => this.toggleActive(property)}> Is there a way to count ...

Filtering an array in Vue using Lodash based on the values of another array

As I continue to learn JavaScript, I have encountered something that is confusing me. Within my Vue data object, I have the following properties: data: { allergenFilter: [], categoryFilter: [], results: {}, }, I am using an array of check ...

Displaying a div on click using Jquery will only impact one div at a time

I am encountering an issue with my WordPress setup. Within my loop, I have a clickable link that toggles a div to show or hide content. However, since each item in the loop uses the same class, clicking on one link activates all of them simultaneously. &l ...

Struggling to integrate data retrieved from a Vue.js API

Once I receive the API call with an attached string input, I successfully get the result. However, I am struggling to incorporate it into my frontend. I have attempted various solutions found online without success and cannot seem to grasp the concept. Her ...

The inverse function for Ember Handlebars helper options is experiencing an undefined error

With a template in hand, I needed to toggle the display of certain text based on a method's return value. Research led me to the recommendation of using handlebars helpers for this purpose. So, I implemented a resetPassword helper within the controlle ...

Navigating in next.js

Whenever I run my program, it displays the following error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component ...

Can you explain the concept of (A == B == C) comparison in JavaScript?

Surprisingly, the comparison I expected to fail was this: var A = B = 0; if(A == B == 0) console.log(true); else console.log(false); To my surprise, it doesn't return true. What's even more astonishing is that console.log((A == B == ...

Tips on saving images to a folder and storing the image paths in a database in MEAN stack with the help of Multer

In my collection, I have a set of images with the following structure: { "productId": {type: String}, "imagePaths": {type: Array} } I am trying to upload multiple images and save their respective image paths to the database. After some research, I found ...

JavaScript - Matching overlapping time intervals

Struggling to develop a custom filter using Javascript, I aim to determine if two time ranges in millisecond getTime() format match. The first time range is retrieved from an object while the second comes from user input for filtering. Currently, my code c ...

Each time I load the page, it displays differently depending on the browser. I'm struggling to understand the reason

Trying to figure out how to make the navigation bar close when a link is clicked and directed to a section instead of a new page. When on a large screen, I want the nav bar to remain open but automatically close when on a small screen (for example, when th ...

Having trouble with installing npm package from gitlab registry

I recently uploaded my npm package to the GitLab package registry. While the upload seemed successful, I am facing an issue trying to install the package in another project. When I run npm install, I encounter the following error: PS E:\faq\medu ...

Adjust the formatDate function in the Material UI datepicker

I recently implemented the material-ui datepicker component with redux form and it's been working great. However, I have encountered a minor issue. Whenever I change the date, it displays in the input field as yyyy-mm-dd format. I would like it to app ...

Explore the various timer functionalities available in Angular.js

I am working on a project that requires displaying two timers on a webpage, each with different start times. The first timer should only show for 5 seconds, and then after 10 seconds, the second timer should be displayed. I am new to Angular and have writ ...

After using `setAttribute`, React is unable to produce any audio

Currently, I am facing an issue with a React component where it should play sound from an array of IDs stored in the database by setting the ID to the src attribute for the source tag. However, this functionality is not working as expected. Interestingly, ...

Choose an option removed upon clicking

I need to remove the option with a value of 0 when the user selects from the dropdown list. Choose: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:select id="CONTEXTE" path="CONTEXTE" onclick="go()" class="s ...

Utilizing JavaScript to Parse Datasnap Output

I am currently working on a project in Delphi where I need to display a list of data in a listbox. However, I am struggling to understand how everything comes together. Luckily, I found a helpful answer that provided me with a solution using a dataset def ...

Dygraphs.js failing to display the second data point

My website features a graph for currency comparison using Dygraphs. Everything was working fine until I encountered this strange issue. https://i.stack.imgur.com/OGcCA.png The graph only displays the first and third values, consistently skipping the seco ...

Issue with $observe in AngularJS

Unable to trigger the $observe function on change. .directive('watchContent', function () { return { restrict: 'A', link: function (scope, elem, attrs) { console.log(attrs.class) attrs.$observe("class", functi ...

Generating a unique user ID similar to Zerodha's user ID using Node.js/JavaScript

For a project I'm working on, I need to create random and unique User IDs. I came across Zerodha's user IDs which are easy to remember. In Zerodha user IDs: The first two characters are always letters followed by four numbers. I want to generat ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...