A guide on utilizing a controller again in AngularJS while adjusting variables according to different routes

My task involves loading a web service and I found the angular method of displaying, sorting, and filtering tables to be very effective. Now, I am looking to enhance this functionality. Depending on the selected link, I want to show different data from the same web service in a similar format. I aim to avoid duplicating code by reusing the controller but I'm facing some confusion. This includes:

  • Displaying a different partial/template URL
  • Loading different URL parameters
  • Mapping certain elements after receiving JSON data

What would be the best approach for handling these changes in configuration? Initially, I tried routing to a variable (

when('/change-requests/:businessUnit'
) and then using it to fetch varying values. However, how can I switch the template URL accordingly? On the other hand, if I simply add a route and load a different URL template (while reusing the controller), how do I adjust the AJAX call to load a different URL? As I am not well-versed in Angular, I might be going about this in the wrong way...

Here are key segments of my original code. While there is more to it, those sections remain unaffected. I have indicated specific sections with inline comments where modifications may be needed based on the selected links.

HTML:

<div ng-view></div>

Router:

$routeProvider.when('/change-requests/business-solutions', {
                    //this template will be different
                    templateUrl: 'js/modules/changeRequests/partials/business-solutions.html',
                    controller: ChangeRequestCtrl
                })

(parts of the) Controller:

function ChangeRequestCtrl($scope, $location) {

                $scope.loaded = false;
                $.ajax({
                    //this url will be different
                    url: url,
                    success: function(json) {
                        $scope.$apply(function() {
                            $scope.changes = json.map(function(row) {
                                //this array map will be different
                                return row;
                            });
                            $scope.loaded = true;
                        });
                    },
                    error: function() {
                        $scope.error = true;
                    }
                });
        }

If my explanation is unclear, please let me know so I can provide further clarification.

Answer №1

To achieve reusability with controller names, it is recommended to utilize the resolve property in conjunction with routes and then reference this resolve property within the controller.

 $routeProvider.when('/change-requests/business-solutions', {
                    //this template will be different
                    templateUrl: 'js/modules/changeRequests/partials/business-solutions.html',
                    controller: ChangeRequestCtrl, resolve: {
            resolvedprop: ['$route', '$q', function ($route, $q) {
               var apiObject = {url: 'abc.com' };                      
               return apiObject     
                     }],
        }
                })


     function ChangeRequestCtrl($scope, $location,resolvedprop) {
       url = resolvedprop.url ;
       }

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

Warning: The React Router v6's Route component is unable to find the origin of the key props

I recently came across an error in my console and I'm unsure which list is causing it. Is there a way for me to trace back the origin of this error so I can pinpoint where to fix it? The error seems to be related to the React Router component, which ...

distinctive information bound to a v-model in Vue

Within my template, I have a select field: li(v-for="user in users", :id="'user_' + user.id") .user-management(@click="toggleShowUser(user)", :id="'user' + user.id") select(v-model="selected" :options="options") In my Vue compon ...

Add another condition to the current JavaScript rule

http://jsfiddle.net/e8B9j/2/ HTML <div class="box" style="width:700px">This is a sentence</div> <div class="box" style="width:600px">This is a sentence</div> <div class="box" style="width:500px">This is a sentence</div> ...

Calculate the total of every pair of numbers within an array

Looking to calculate the sum of pairs of numbers from an array? Here's how to do it: Numbers = [1,2,3,4,5,6....] Sum of Pairs = [3,7,11,...] Appreciate your help ...

Issue with Facebook Open Graph Cache

I'm in the process of developing an application that automatically shares information on Facebook whenever a user downloads a specific music album. The data parsing is functioning correctly: when a user clicks to download album 1, the information is e ...

Unable to submit POST request in Node.js

Seeking assistance to resolve a persistent error that has been causing me trouble for quite some time. This issue is preventing me from adding data to my database successfully. Any help or guidance on this matter would be greatly appreciated. This sectio ...

Having trouble implementing a multi-level sub menu in a popup menu in Vue.js?

data: { menuItems: [{ name: 'Item 1', children: [{ name: 'Subitem 1' }, { name: 'Subitem 2' }, { name: 'Subitem 3' }] }, { ...

Ways to update a JSON object within an array of objects

I've got an array of objects // Extracted from the database $scope.users = [{"$id":"1","UserID":3,"Name":"A","Selected":false},{"$id":"2","UserID":4,"Name":"B","Selected":false},{"$id":"3","UserID":5,"Name":"C","Selected":false},{"$id":"4","UserID":6 ...

Adjusting the border-right size based on scroll position

Apologies if this question seems trivial, but I am completely new to coding in HTML and JavaScript. I understand that I can make some changes based on scroll position, but right now I'm a little confused. I want to increase the height of a box as the ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

Potential data retention issue within website interface (potentially stemming from AJAX requests)

After setting up an AJAX request on my JavaScript-enabled (+jQuery) webpage to fetch JSON data every 5 seconds, I encountered a major issue. I accidentally left my application running overnight, only to find my computer completely frozen the next morning. ...

Examining the focus-next custom directive in Angular JS

I have recently developed a custom directive to tackle some focus-related issues within my application. Directive Code: (function() { angular.module("FocusNextModule", []).directive("focusNext", function() { return { restrict: "A" ...

Comparing JSON and JavaScript object arrays: Exploring the differences in outcomes and strategies for achieving desired results

Although it's not valid JSON, I've found that by declaring this as a variable directly in my code, I can treat it like an object. <script> // this will result in object var mydata = { users: [{ person: { ...

Switching between classes using jQuery

I'm working on implementing a play and pause button for a video, and I'm facing an issue with switching the class when the button is pressed. What I want is that when the pause button is clicked, the class changes to something else, and vice vers ...

The iisnode encountered an issue with HRESULT 0x6d resulting in a status code of 500 and a substatus of 1013

Despite trying multiple solutions, none seemed to work for my Node.js website hosted on Windows IIS with iisnode. Everything was running smoothly until today when I encountered an interesting situation. Let's say my domain is cdn1.site.com and it&apos ...

Limiting access to all routes except one

Lately, I've been exploring the combination of ExpressJS + AngularJS and encountered a bit of a tricky situation. My objective is to create a single login page and a dashboard page. By using Passport + MongoDB for user authentication, my plan is to v ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Transmitting the data from the input field

I'm currently stuck trying to figure out the logic behind my Ajax form submission. I am attempting to POST my form using Ajax and send certain values in the correct manner. Here is an example of my form: <form method="post" action="~/AJAXcalls/ca ...

Using Meteor package to efficiently import JSON arrays into mongoDB

I am currently working on developing a meteor package that will allow users to import JSON files into collections in a mongoDB. However, I'm uncertain about the feasibility of this task. The idea is for the user to upload a JSON file and specify the ...

jQuery submission not activating

Within a single HTML file, I have two separate forms that operate independently of each other. The issue I am currently encountering is that the $(form).submit((event)=>{code}) function only works on: <form id="mainForm" action='' ...