The map function will produce a result of -1 when utilizing the $stateParams parameter

When attempting to pass a variable to a page, the URL I'm using is:

http://localhost/project/#/app/intro/1

After routing to my controller, everything seems fine until I try to use the map function on an array in my controller - that's where the problem arises!

The code in question looks like this:

console.log($stateParams.userId); // returns 1
var ePos = $rootScope.data.users.map(function (x) {
    return x.id;
}).indexOf($stateParams.userId);
console.log(ePos); // returns -1

Interestingly, when I switch to using static data instead of the variable, everything works as expected:

console.log($stateParams.userId); // returns 1
var ePos = $rootScope.data.users.map(function (x) {
    return x.id;
}).indexOf(1);
console.log(ePos); // returns 0

Answer №1

If you're encountering issues with the working plunker provided here, it may be due to the fact that the id is being treated as a string when it should be an integer. Take a look at this example:

// In this code snippet, we specify that id should be treated as an INT
.state('int', {
   url: "/int/{id:int}",
   templateUrl: 'tpl.html',
   controller: 'MyCtrl',
})
// Here, id remains a string "1"
.state('str', {
   url: "/str/:id",
   templateUrl: 'tpl.html',
   controller: 'MyCtrl',
})

Ensure to use the correct format for integers and strings in your links:

// Links returning id as a number
<a href="#/int/1">int/1</a>
<a ui-sref="int({id:2})">int({id:2})</a>

// Links having string as id
<a href="#/str/3">str/3</a>
<a ui-sref="str({id:4})">str({id:4})</a>

Feel free to explore the example provided here.

In an extension (view extended plunker), consider defining states as follows:

.state('app', {
  url: "/app",
  templateUrl: 'tpl.app.html',
})
.state('app.userIntro', {
  url: "/intro/{userId:int}",
  views: {
    'menuContent': {
      controller: 'UserIntroCtrl',
      templateUrl: "templates/intro.html"
    }
  }
})

You can call these states using the following links:

<a href="#/app/intro/1">app/intro/1</a>
<a href="#/app/intro/2">app/intro/2</a>
<a ui-sref="app.userIntro({userId:3})">int({userId:3})</a>
<a ui-sref="app.userIntro({userId:4})">int({userId:4})</a>

Don't forget to check out the extended version for more details.

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

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

Transfer information from the server to the client using NodeJS and Express

I am encountering an issue with sending data from my express server to the client side. I have implemented app.post and app.get, however the problem is that the request needs to originate from the client side. My requirement is to send the data from the se ...

Stack the labels of separate datasets on top of each bar in a bar chart using Chartjs: How can this be achieved?

chart.js 4.4.2 chartjs-plugin-datalabels I am aiming to achieve this effect const chartCtr = document.querySelector('#temp-chart1') as HTMLCanvasElement; new Chart(chartCtr, { type: 'line', plugins: [ChartDataLabels], opt ...

Strategies for transferring data between controllers and configuration files in AngularJS

I'm attempting to pass a variable to the angular js config, Here is my JavaScript app: var app = angular.module('myApp', ['ngMaterial', 'sasrio.angular-material-sidenav', 'ui.router']); app.controller('ba ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

turn off the final link item

I am currently working with Angular 1.6 and I am attempting to disable the last link in the sidenav. However, for some reason, the first item is being disabled instead. Here is the code snippet: <li ng-repeat="item in nav.sideNavListOne" ui-sref-acti ...

Ensuring Vue.js correctly re-renders an array item

In my vue.js 2 project, I am working with an array that has the following structure: data() { return { ports: [ { id: 1, name: "example", "age": 10, scores: [ {index: 1, value: 100}, {index: 2, value: 200} ]}, { id: 2, ...

Is it possible to use setState after a setTimeout to unmount a component?

Can anyone help me find the issue with my code? I am attempting to clear an error message after a specific duration, but it's not working as expected. I'm puzzled about what might be causing this problem. export default class MyError extends Com ...

Retrieving data from an Array containing a mix of string and integer values represented as strings, organized by the length of the

Imagine you have an array structured like this: employeeArr = ['Steve', '80000', 'Jen', '90000', 'Bob', '40000'] Where employeeArr[0] and employeeArr[2] represent employee names, and employeeA ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

Organizing child directives within a main template

Currently, I am in the process of creating a new directive called "info-card". My vision is to utilize it in the following manner: <info-card theme="light"> <info-header> <h2>Hello World</h2> </info-header> ...

Using PHP to detect changes in input fields upon page load with jQuery

I have a jQuery snippet on my page: $( document ).ready(function() { $("#URL").on("input load", function(e) { console.log(e.type) .... }); }); Further down the page, I also have... <input id="URL" type="text" value="<?=$_GE ...

Is there a way to reach my vue instance while inside a v-for iteration?

When using a v-for loop, I encounter an error: <div v-for="index in 6" :key="index"> <div class="card h-100" style="margin-top: 200px;"> <a href="#"> <img ...

Show a toast message and reset the form upon submission

Here I have created a contact form using HTML, CSS, and JavaScript. However, I'm facing an issue where the form redirects me to a page displaying the submitted details after clicking the submit button. I want to display a toast message instead and res ...

Experiencing difficulties with knockout bindings

I have a situation where I have multiple tabs labeled A, B, and C, and upon loading the 'C' tab, the model properties should data-bind to tab 'C'. I am encountering an issue with data binding. These three tabs (A, B, C) are located ins ...

Attempt to insert an HTML page containing a script into a different webpage

Greetings and thank you for taking the time to read my first post here :) I have a script that is functioning properly, here is a simplified version of my page1.html: <html> <head> <script type="text/javascript" src="js/jquery-1.6.4.mi ...

Is there a resource available that can help me create a jquery/ajax image slider/carousel similar to this?

One thing that really caught my eye is how cnn.com has implemented this feature. I think it would be a great addition to the website I'm currently working on. I particularly like the page numbering, as well as the first, previous, next, and last butto ...

An error was encountered: object does not possess the function 'tooltip'

I have been attempting to display a tooltip on a textbox using jQuery scripts within a web form that utilizes a Master Page. While everything appears to be working fine when I run my code, I am encountering the above error in the resources folder of the DO ...

React Material-UI select component malfunctions when I enclose the menu item within a Tooltip wrapper

Here is a snippet of my code: return( <FormControl sx={{ m: 1, minWidth: 80 }}> <InputLabel id="demo-simple-select-autowidth-label">Age</InputLabel> <Select labelId="demo-simple-select-autowidt ...

Creating consistently sized rows of Bootstrap columns - with either equal heights or equal spacing between each row

It would be great if bootstrap had a built-in feature where it automatically assigns the wrapper div of any item with a height based on the height of the largest div. In this example on JSFiddle, you can see that I have different heights for the video-ite ...