The concept of navigation and passing parameters in Angular.js

Attempting to customize the standard user module of MeanJS, I added a new route:

state('users', {
            url: '/users/:username',
            templateUrl: 'modules/users/views/view-profile.client.view.html'
        });

In my view:

data-ng-controller="ViewProfileController" data-ng-init="findUser()"

I also included $stateParams in my controller. However, when I try to access the username parameter in my ViewProfileController using the findUser function like this:

console.log($stateParams.username)

It returns undefined.

When I adjust the route as follows:

state('users', {
            url: '/users/:username',
            template: function ($stateParams){
                return $stateParams.username;
            }
        });

The username is correctly returned. I'm unsure what might be missing or incorrect. Any suggestions?

Edit: Below is my complete controller code

'use strict';

angular.module('users').controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication', 
function($scope, $http, $location, Users, Authentication, $stateParams) {
    $scope.user = Authentication.user;

    $scope.findUser = function () {
        console.log($stateParams);
        ...
    };
}
]);

Answer №1

Your dependencies in the controller function need to match the order of parameters:

'use strict'; 
angular.module('users')
.controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication',
  function($scope, $http, $stateParams, $location, Users, Authentication) { 
    $scope.user = Authentication.user; 
    $scope.findUser = function () { 
      console.log($stateParams); 
    }; 
  }
]);

Answer №2

It would be more efficient to use a controller instead of a template in this scenario.

Update your code by replacing template: with the following snippet:

controller: function($routeParams){
    console.log('userID: '+$routeParams.userID);
}

For a comprehensive example showcasing this feature, click here

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

React is unable to locate an import statement for Material UI components

I am facing an issue while incorporating material UI components into my React project. The error message I receive is related to an invalid import. Snippet from My Component File import React from 'react' import './middle.css' import Mi ...

"Utilizing a dynamic global variable in Node.js, based on the variable present in

I'm looking to achieve the following: var userVar={} userVar[user]=["Values"]; function1(user){ //calculations with userVar[user] } function2(user){ //calcula ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Trouble encountered when implementing setInterval in Next.js

While working on a progress bar component in Next.js and tailwind.css, I used JavaScript's setInterval() function for animation. Below is the code snippet: import React, { useState } from "react"; const ProgressBar = () => { let [progress, setPr ...

Property usedJSHeapSize in Chrome

After doing some research online, I found that the documentation on this topic is quite lacking. I am currently dealing with a significant memory leak in my code and have been using: window.performance.memory.usedJSHeapSize However, it seems like the val ...

Tips on avoiding blurring when making an autocomplete selection

I am currently working on a project to develop an asset tracker that showcases assets in a table format. One of the features I am implementing is the ability for users to check out assets and have an input field populated with the name of the person author ...

Chat Bot - EmbedMessage

JavaScript is still very new to me and I find the actual code quite challenging to grasp. However, I do have one specific question - how can I display the "cahbResponses" in a MessageEmbed? Despite consulting the Discord JS guides on MessageEmbeds, I' ...

Protect database entries from cross-site scripting attacks

I have a project in progress where I am developing an application that extracts text from tweets, saves it to the database, and then presents it on the browser. I am currently concerned about potential security risks if the text contains PHP or HTML tags. ...

Guide on syncing Bootstrap 4 sliders using a single set of controls

Is it possible to synchronize a bootstrap 4 carousel with controls to a carousel without any controls? 1) When the control arrows are clicked, both carousels will slide simultaneously. 2) Hovering over either carousel will pause both carousels from slidi ...

Struggling with implementing Mobile Navigation menu

I'm struggling to implement a mobile menu for my website. After adding the necessary code, when I view the page in a mobile viewport, all I see are two sets of periods ("..."). However, unlike in the code snippet provided, the list does appear on the ...

Understanding the Importance and Benefits of Using the Classnames Utility in React Components

Can you break down for me the purpose of utilizing the Classnames utility in React code? I've reviewed the Classnames documentation, but I'm still struggling to comprehend why it is used in code like this: import classnames from 'classnames ...

Problem encountered with modal and JavaScript: Uncaught TypeError: Unable to retrieve the property 'classList' of null

Trying to implement a modal feature for the first time but encountering an error when clicking the button. Unsure if I'm following the correct procedure as a JS beginner. Any assistance would be appreciated. ERROR { "message": "Uncaugh ...

Popup showing values that are not defined

I've encountered an issue with tooltips on my bar graph. The tooltips should display the values of boarding and alightings corresponding to each stopname column, but I'm seeing undefined values like this Below is my code snippet: <!DOCTY ...

Adding a div beside an input element - step by step guide

When creating an input field in my code, I followed these steps: var inputVal = document.createElement("input"); inputVal.setAttribute("type", "checkbox"); inputChek.onchange = select; inputChek.setAttribute("value", title); //inputChek.after(sortDiv); ...

Tips for showing an alert when incorrect login credentials are entered on a login form

<?php include('includes/config.php'); if(isset($_POST["submit"])){ $empid=$_POST["empid"]; $pass=$_POST["password"]; $query=mysqli_query($conn,"SELECT employee_id, fname,lname,empid,password, status, role FROM employee where empid='$emp ...

Discover the art of concurrently listening to both an event and a timer in JavaScript

Upon loading the page, a timer with an unpredictable duration initiates. I aim to activate certain actions when the countdown ends and the user presses a button. Note: The action will only commence if both conditions are met simultaneously. Note 2: To cl ...

What is the process of initializing divs in DataTables?

My application has a DataTable installed, but I encountered an error message stating "DataTables warning: Non-table node initialisation (DIV). For more details about this error, please visit http://datatables.net/tn/2". I'm aware that DataTables is d ...

The attribute 'split' is not found on the never data type

I have a function that can update a variable called `result`. If `result` is not a string, the function will stop. However, if it is a string, I then apply the `split()` method to the `result` string. This function always runs successfully without crashin ...

"How to eliminate the hash symbol from a URL using react-router-dom in a React.js

Recently started learning react.js and running into an issue with the URL structure while using react-router-dom v6 in my project. Specifically, I'm finding a problem with the # symbol in the URL. For instance: {url}/#/dashboard I would like it to b ...

Ng-repeat loop: Checkbox checked when two values are matched

Is there a way to automatically check a checkbox within an ng-repeat if two specific values are true? For instance: <div ng-repeat="item in list"> <input type="checkbox" ng-checked="((item.value1 == true) + (item.value2 == true))" /> < ...