Managing various route parameters within a single controller

In my development project, I have a unique setup where a single controller handles different routes with varying parameters. Here's a snippet from my routes.js file:

.when('/event/:eid/edit-question/:qid', {
            templateUrl: 'views/edit-question.html',
            controller: 'eventController',
            controllerAs: 'eventCtrl',
            resolve: {
                "check": function (authService, $location) { 
                    if (!authService.isLoggedIn()) {
                        $location.path('/login');
                    }
                },
                "params": function ($route) {
                    return $route.current.params; 
                } 
            }   
        })   
        .when('/event/edit-event/:eid', {        
            templateUrl: 'views/edit-event.html',      
            controller: 'eventController',     
            controllerAs: 'eventCtrl',       
            resolve: {       
                "check": function (authService, $location) {    
                    if (!authService.isLoggedIn()) {        
                        $location.path('/login');  
                    }       
                },      
                "params": function ($route) {         
                     return $route.current.params;       
                }     
            }   
        })

I've implemented logic to resolve the route params before loading the controller. Inside my controller, the functions are structured as follows:

myApp.controller('eventController', ['$location','$rootScope', 'params', 'authService', 'apiService', function ($location,$rootScope, params,authService, apiService) {
 let dash = this;
//all the route parameters will be resolved and stored here
 dash.params = params;
 //get the details of an event
    dash.getTheEventDetail = () => {
        apiService.getEventDetail(dash.params.eid).then(function successCallBack(response){
           console.log(dash.params.eid);
            dash.eventDetail = response.data.data;
        });
    }
    dash.getTheEventDetail();

    //get the detail of a question for the qid passed as parameter

    dash.viewQuestion = () => {
        console.log(dash.params.qid);
        console.log(dash.eventDetail); 
        dash.questionDetail = dash.eventDetail.questions.filter(question => question._id === dash.params.qid);
        console.log(dash.questionDetail);
   }

However, I encountered an issue where the viewQuestion function gets executed before getTheEventDetail when accessing the route /event/:eid/edit-question/:qid, leading to dash.eventDetail remaining undefined. The call to viewQuestion occurs on initialization of the controller in the edit-question view like this.

<div ng-init="eventCtrl.viewQuestion()"></div>

I've considered calling the viewQuestion function at the end of getTheEventDetail() as a workaround, but this would result in viewQuestion being triggered every time getTheEventDetail is called. Any suggestions on a better approach to handle routeParams in this scenario?

Answer №1

Have you considered utilizing the $routeParams service within your controller instead? It appears that viewQuestion relies on the successful execution of the getEventDetail method from apiService to set the eventDetail. If this is indeed the case, it might be beneficial to eliminate the ng-init directive and incorporate the view question within your callback to ensure that the promise has been fulfilled before accessing data that may not yet exist. Additionally, since the filter function returns an array and you are searching by ID, it seems like you might prefer a single question rather than an array. In such a scenario, specifying an index of [0] or using Array.find may be necessary.

Although I'm unsure about the specific desired outcome, here's a potential solution provided below (not tested). Hope this assists you.

myApp.controller('eventController', ['$location','$rootScope', routeParams', 'authService', 'apiService', 
    function ($location,$rootScope, $routeParams,authService, apiService) {
     let dash = this;

     //retrieve event details
        dash.getTheEventDetail = () => {
            apiService.getEventDetail(dash.params.eid)
                .then(response => {
                    dash.eventDetail = response.data.data;
                    if ($routeParams.qid) {
                        dash.viewQuestion()
                    }
            });
        }
        dash.getTheEventDetail();

        //retrieve question details based on qid parameter

        dash.viewQuestion = () => {
            dash.questionDetail = 
                dash.eventDetail.questions.filter(question => question._id === $routeParams.qid);
            console.log(dash.questionDetail);
    }            
}

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

Discover specific element details using the id with Strapi and React

I am currently studying react with strapi and I have encountered an issue. I have successfully displayed all elements from a database, but I am facing a problem when trying to display specific information on clicking an element. Although I can retrieve t ...

Executing a long job in PHP (Laravel) while simultaneously making an AJAX call

Looking to create a real-time progressing bar? I attempted to incorporate this example into my Laravel project but seem to have missed a step. Here is my HTML and JavaScript code: <div style="border:1px solid black;width:500px;height:80px"> &l ...

AngularJs has the ability to parse dates effectively

So, I have this date: /Date(1451602800000)/. My goal is to display it in the 'short' format. Even after attempting {{myDate | date:'short'}}, the output remains as /Date(1451602800000)/ ...

Conceal or reveal content within two dividers

Two <div> elements are present, referred to as div1 and div2. Before clicking submit, I want div1 to be displayed and div2 to be hidden. However, after submitting, I want div1 to hide and div2 to show. The code within kanjiconverter.php is: < ...

Escaping quotes in JavaScripts is an important skill to

I have a table called posts. When I add a title enclosed in quotes ("This the new") to the posts table and then try to delete the post using an onclick javascript function, I encounter the following issue: echo "<td><a class='btn btn-danger& ...

Utilize Bootstrap's JavaScript feature to prevent form submissions when there are invalid fields present and to address any issues where the form is not functioning properly

Utilizing Bootstrap version 4, I have a contact form within index.php that requires user validation. Upon submission, users should be alerted to any missed required fields. For instance, if a user submits without completing any fields, they should see the ...

Issues involving JavaScript and jQuery

As a beginner in the world of JS and jQuery, I have encountered a problem that I am seeking assistance with. I am trying to use a script to insert content into a page, but I am facing a roadblock that I can't seem to overcome. Here's the specific ...

A React child error has occurred in Next.js due to invalid objects being used

Within my project, I have integrated the latest version of next.js and encountered an issue where objects are not valid as a React.js child. https://i.stack.imgur.com/MCO7z.png The problem arises after importing the Head component from Next.js and implem ...

The JavaScript code in Three.js is experiencing issues when running in a secure HTTPS environment

After transitioning my website from http to https, I encountered an issue with one of my projects. The background using the Three.js library in this random generator does not show up when the URL is https. However, when the URL is http, the generator wor ...

Exploring Angular's nested categories with the power of *ngFor loop

I am facing a challenge with an undefined number of arrays that can be nested without limit. This is for the "filtering" section on a page where products are listed. However, I am struggling to dynamically create this structure on the HTML side. [ { ...

What is the best way to effectively apply a mask within a PixiJS container so that its color does not display upon page refresh?

After implementing the code snippet below to add a mask in a container, I encountered an issue where upon clicking the refresh button on the page (chrome), the pixi stage would turn completely white until the refreshing process is completed. Can anyone p ...

Issue encountered when attempting to serve JSON response using Node.js, express, and MongoDB after the initial response

I have been experimenting with creating simple RESTful APIs using Node.js, Express, and MongoDB. For this purpose, I am utilizing the Node.js-MongoDB driver in conjunction with the Express framework. const MongoClient = require("mongodb").MongoClient cons ...

Deploying a WebAPI to the api directory of an Angular app hosted on IIS results in 500 errors when making requests

I have been working on developing an angular application with a WebAPI 2 backend. The two components are in separate repositories, directories, and environments - the angular project is not part of a Visual Studio project and I am using WebStorm to work on ...

How can we initiate the AJAX request right away while also making sure the page is fully loaded before adding

One trick I've discovered is that by submitting an AJAX request in the <head> section of my webpage, I can avoid a minor flicker on page load when loading content via AJAX. Of course, this method still needs some refining to handle longer AJAX r ...

Searching for ways to filter out specific tags using regular expressions

Can anyone provide a quick solution to help me with this issue? I am trying to remove all html tags from a string, except for the ones specified in a whitelist (variable). This is my current code: whitelist = 'p|br|ul|li|strike|em|strong|a', ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

Learn how to join a comma with a space in AngularJS

My sequence of strings is "aby,abraham,issac,rebecca,job,david,daniel" and I want to insert a space after each comma. I am assigning the value using ng-bind and showing the result using ng-show. I cannot use the join function as the data is retrieved as a ...

What steps can be taken to modify this jQuery code so that any changes made are also saved to localStorage

I have successfully used jQuery to change the background color of all my divs with the same class (userNumber1) when I check its checkbox. However, I am now looking for a way to save these changes to localStorage, so that they persist each time the page is ...

retrieving attribute values from JSON objects using JavaScript

I am struggling to extract certain attribute values from a JSON output and use them as input for a function in JavaScript. I need assistance with this task! Below is the JSON data that I want to work with, specifically aiming to extract the filename valu ...

AngularJS ECMAScript 6 Directive

I am facing an issue while working on an angular es6 application. The problem lies with a directive that I have implemented. Below is the code snippet: export default class RoleDirective { constructor() { this.template=""; this.restrict = ' ...