Having trouble retrieving state parameters when trying to launch a modal in AngularJS

When the "view detail" link is clicked, I wanted to open a modal for a detailed view of a specific user. However, I encountered an issue where I couldn't retrieve the user ID in the resolve attribute of $uibModal.open(). Strangely enough, the ID is available in the inline controller function.

.state('dashboard.users',{
    url:'/users',
    cache:false,
    views:{
        'listusers':{templateUrl:'./partials/users/list.tpl.html?time='+ Math.random(),controller:'UsersController'}
    },
    authenticate:true
})
 .state('dashboard.users.view',{
        url:'/view/:id',
        parent:'dashboard.users',
        cache:false,
        authenticate:true,
        onEnter:['$uibModal',function ($uibModal) {
            $uibModal.open({
                templateUrl:'./partials/users/view.tpl.html',
                keyboard:false,backdrop:'static',
                size:'sm',
                resolve:{
                    userData: function($stateParams, $state) {
                         console.log($stateParams.id);// unable to get id
                    }
                },
                controller:function($scope,$uibModalInstance,$state,UsersFactory,userData,$stateParams){
                    $scope.closeLoginModal=function(){
                        $uibModalInstance.dismiss('cancel');
                        $state.go('dashboard.users');
                    }
                  console.log($stateParams.id); // id is avaliable over here
                }
            });
        }]
    });

HTML

<tr ng-repeat="i in users">
    <td>{{ i.id }}</td>
    <td>{{ i.name }}</td>
    <td>{{ i.email }}</td>
    <td>{{ i.username }}</td>
    <td>{{ i.website }}</td>
    <td><a ui-sref="dashboard.users.view({id:i.id})"><button class="btn btn-default btn-xs">View</button></a></td>
</tr>

Any assistance on what may be going wrong in my implementation would be greatly appreciated.

Answer №1

There are a few key points to consider, but let's address your question first. When it comes to onEnter callbacks, they indeed have access to the resolves of the state. However, in the code provided, the resolves are placed inside the callback, which is not the correct approach. It is recommended to move the resolves to the state declaration where they belong.

Furthermore, having a controller inside the callback will not work as intended. Instead, it is advisable to declare the controller in the state and consider moving it to a separate file. This approach not only prevents clutter in the config.routes but also simplifies unit testing.

While using onEnter is commendable, it is not commonly seen in practice. A better approach would be to centralize all modal functionality within the controller (separate file) and trigger it from the controller's constructor for better organization and efficiency.

Answer №2

Here is a code snippet that demonstrates how to resolve a problem by injecting $stateParams into the OnEnter function:

onEnter:['$uibModal','$stateParams',function ($uibModal,$stateParams) {
            var id = $stateParams.id;
            $uibModal.open({
                templateUrl:'./partials/users/view.tpl.html',
                keyboard:false,backdrop:'static',
                size:'sm',
                resolve:{
                    userData: function($state) {
                         console.log(id); // id available
                    }
                },
                controller:function($scope,$uibModalInstance,$state,UsersFactory,userData,$stateParams){
                    $scope.closeLoginModal=function(){
                        $uibModalInstance.dismiss('cancel');
                        $state.go('dashboard.users');
                    }
                    console.log($stateParams);
                }
            });
        }]

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

Gathering information from the server once it has completed its processing phase

Looking to retrieve data from my server after processing it. Specifically, I want to transfer the processed information to the front end. Situation: A document gets uploaded to Google Cloud, data is extracted and stored in Firestore, then that extracted d ...

AngularJS: Click on image to update modelUpdate the model by clicking

I am a newcomer to AngularJS and I am attempting to update my model after the user clicks on an image. Below is the code for this: <div class="col-xs-4 text-center"><a ng-model="user.platform" value="ios"><img src="ios.png" class="img-circl ...

I am interested in utilizing $axios in conjunction with Vuex constants for my project

My Dream Becoming Reality I frequently use this.$axios, so I attempted to store it in a constant, but unfortunately, it did not work as expected. Despite reading the official documentation, I couldn't grasp the reason behind this issue. Could it be d ...

Unique trigger for clicking events with customizable widgets in JQuery

I'm in the process of developing a jquery widget that functions similarly to a menu bar, featuring two buttons - ButtonOne and ButtonTwo. With my HTML code and associated styles in place, I've been focusing on creating a "hello world" widget. / ...

Eliminate FormData usage from the Next.JS backend application

Looking to replicate the steps outlined in this guide: https://medium.com/@_hanglucas/file-upload-in-next-js-app-router-13-4-6d24f2e3d00f for file uploads using Next.js, encountering an error with the line const formData = await req.formData();. The error ...

Encountering a Problem When Exporting a Class Using Require

I find myself struggling with a particular detail that eludes me. Despite exploring numerous suggested solutions found through Google, I am overwhelmed by the uncertainty of what actually works. Here is MyProject on Replit and the problematic class I&apos ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

Using ES6 to generate objects within other objects

Dealing with data from a local API can be challenging, especially when you have limited control over the incoming data. However, I am looking to transform the data post my API call using a custom function. This is my current approach transformArray = () ...

What is the best way to retrieve the Axios response using Express?

I've recently delved into working with Express and I'm currently struggling with making an Axios request using route parameters, and then updating some local variables based on the response. Here's a snippet of what I've been working on ...

AngularJS, Implement a "read more" feature after a specified number of characters

Is there a way to implement a "read more" tag in Angular that will automatically appear if a string exceeds 100 characters? I've been searching for an example without any success. Any help would be appreciated. Edit: -- SUCCESS! Thanks to Don' ...

Efficient ways to clear all input fields within a React div component

import "./App.css"; import { useState } from "react"; import { useSelector, useDispatch } from "react-redux"; import { addUser} from "./features/Users"; function App() { const dispatch = useDispatch(); const use ...

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...

Generate a two-dimensional array of pixel images using HTML5 canvas

Hey everyone, I'm trying to copy an image pixel to a matrix in JavaScript so I can use it later. Can someone take a look and let me know if I'm using the matrix correctly? I'm new to coding so any help is appreciated. Thanks! <canvas id= ...

Deploy a Node.js websocket application on Azure Cloud platform

After smoothly running on Heroku, the server app encountered a problem with startup after moving to Azure. Below is the code snippet: const PORT = process.env.PORT || 2498; const INDEX = '/index.html'; const server = express() .use((req, res ...

Exploring the Function Scope within ViewModel

I have been facing an issue while trying to call a function from my ViewModel within a foreach loop. It seems like the function goes out of scope as soon as I call it. Being new to JavaScript, I am struggling to understand why this is happening. Here is t ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

Working with double quotes within variable in JavaScript

I am currently working on dynamically creating HTML tags using JavaScript. Please take a look at the code snippet below: function getPhotosSuccess(data) { if (data.d.results.length > 0) { var response = data.d.results; var innerht ...

Tips for utilizing component-specific sass files with Next.js

Having a background in React, my preference is to use SCSS files at the component level just like I did in my React app. However, I encountered an issue when trying to do so in Next.js: Global CSS cannot be imported from files other than your Custom < ...

Modifying the State array is beyond my control

I'm facing an issue passing the codes correctly here, so I'll explain the problem using images. (REMEMBER: All these are within the same component) Issue: I have a single state value: state = { base: [ {tomato: false}, {egg: true} ], ...

Utilizing ui-router for handling multiple views within a higher-level abstract component

I am currently facing challenges while structuring a route hierarchy using ui-router. In my project, I have organized templates into three layers: guest template, user template, and admin template. The structure of my index.html page is as follows: <h ...