Utilize Angular components and controllers that can be customized with varying parameters

I've been tasked with working on an Angular 1 frontend that communicates with a fairly standard REST API. The setup involves basic HTML views paired with controllers that interact with a consistent base URL for each controller, such as /customer in this simplified scenario:

Controller

app.controller('customerCtrl', function($scope, $http) {
    $scope.loadCustomer = function() {
        $http.get('/customer/'+$scope.id) 
             .then(function(response) {
                 $scope.customer = response.customer;
             });
    };
    $scope.loadCustomerData = function() {
        $http.get('/customer/'+$scope.id+'/data') 
             .then(function(response) {
                 $scope.customerData = response.data;
             });
    };
});

View

<div ng-controller="customerCtrl">
    <input type="text" ng-model="id"></input>
    <button ng-click="loadCustomer()">Load Customer</button>
    <div>{{ customer.name }}</div>
    ...
    ...
</div>

Presently, everything is working smoothly. However, a new group of users now needs access to the application. Although the frontend view and controller logic remain unchanged, they need to communicate with a different backend base URL, say /externalCustomer. This means the load function call would have to use a different URL structure like

$http.get('/externalCustomer/'+$scope.id)
.

Furthermore, these new users require distinct URLs for their views. For instance, if the current view is accessed at http://app.com/#/customerView, the new view would be located at

http://app.com/#/externalCustomerView
.

Given the extensive length of the existing files, I'm seeking a solution where I can avoid duplicating code or causing divergence in logic. Ideally, I'd like to find a way to reuse both the views and controllers by potentially passing a base URL parameter and/or view URL. Any guidance on how to approach this challenge would be greatly appreciated.

Answer №1

When setting up your routes:

$routeProvider
        .when('/:baseUrl', {
            templateUrl: 'public/app/customerView.html',
            controller: 'customerViewCtrl',
            controllerAs: 'customerViewCtrl'                           
            }
        });

Make sure to inject $route in your controller and retrieve the 'baseUrl' parameter as follows:

$http.get('/'+$route.current.params.baseUrl+'/'+$scope.id+'/data') 
         .then(function(response) {
             $scope.customerData = response.data;
         });

This allows you to dynamically set the baseURL based on whether it's an externalCustomer or a customer.

Alternatively, consider this approach:

$routeProvider
        .when('/customerView', {
            templateUrl: 'public/app/customerView.html',
            controller: 'customerViewCtrl',
            controllerAs: 'customerViewCtrl',
            baseUrl: 'customer'               
            }
        }).when('/externalCustomerView', {
            templateUrl: 'public/app/customerView.html',
            controller: 'customerViewCtrl',
            controllerAs: 'customerViewCtrl',
            baseUrl: 'externalCustomer'                
        })

And in your controller, again inject $route and access the 'baseUrl' like so:

$http.get('/'+$route.current.baseUrl+'/'+$scope.id+'/data') 
         .then(function(response) {
             $scope.customerData = response.data;
         });

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

Deactivate options in the dropdown selection

Is there a way to disable specific values in a dropdown list? While exploring a solution here, I discovered that adding a disabled style to <a> should disable the element. However, when I tried this method on dropdown element B, it did not work as e ...

Updating fields in MongoDB using dot notation

In my Mongo Schema, I have defined the following structure: var OrderSchema = new Schema({ postcode: String, ... status: { last_check: { type: Date }, date: Date, code: String, postnum: String, text: Str ...

Why hasn't the styles folder been generated in Nuxt 3?

After running the command "npx nuxi generate," the css folder does not seem to be created in the static site. What could be the issue? package.json: { "private": true, "scripts": { "build": "nuxt build", "dev": "nuxt dev", "generate": ...

Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example: { _id: "someId", profile: { username: "oliv", friendRequests: [ { fromUserId: "anId", accepted: false, created: " ...

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

What is the best way to incorporate personalized events into an array using JavaScript?

Imagine we have an array called var arr = [1, 2, 3]. I am looking for a way to create a method that can observe any changes made to this array. The idea is something similar to the following: arr.on('change', function () { // perform some ac ...

"Upon inspection, the TrackerReact Container shows that the user's profile.avatar is set, yet the console is indicating that

Within my app, I designed a TrackerReact container named ProfileSettingsContainer. This container retrieves the user data with Meteor.user() and passes it to a function called user(), then sends this information to the ProfileSettings component. The main o ...

Resolving problems with image dimensions in Angularjs and ionic framework

I'm attempting to achieve a design where the first image occupies 50% of the screen's height and 100% of its width, while the second image does the same. Please refer to the image below: https://i.sstatic.net/nwmRP.jpg ...

Google Scripts: Generating a set of data to include in an email

As a newcomer to Google Script and JavaScript, I'm on a mission to email a list of file names extracted from a spreadsheet. The names reside in a column within my sheet, and after defining a variable called "newfiles" to cherry-pick only the necessary ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

Executing code before a component mounts in ReactJs: What to do now that componentWillMount is no longer recommended?

Before my component mounts, I want to redirect the user to the home page based on a condition: componentWillMount(){ console.log("componentWillMount is called.") let userHasNotChosenOpportunity = true if (userHasNotChosenOpportunity) ...

Strategies for Passing Select ID Using JavaScript/jQuery

Currently, I am working on resolving a problem that is detailed in my post here jQuery/js separating 2 drop down values. I am wondering how to properly pass #dropdown1 in the following code: <select id="dropdown1" multiple="multiple" class="multiselect ...

incorporate information into D3 with React

Greetings! I am currently working on a line graph that should display dynamic data. In cases where no data is provided, it will simply show a straight line. My current challenge lies in passing the props to the line graph component. var data `[ { &quo ...

Show and hide menu items without automatically scrolling the user back to the top of the page

I am currently working on a project where I have an image button that toggles between expanding and collapsing a menu using JavaScript. The issue I am facing is that every time the button is clicked, it takes the user back to the top of the page. My goal ...

Tips for Configuring a Nestjs Query Using TypeORM to Retrieve Several Entries

When I send this specific URL from my Angular application: http://localhost:3000/api/skills?category_id=2 The main issue revolves around how to modify the code in order to successfully retrieve all skills with a category_id of 2. It is important to note ...

Middleware in Express.js designed to alter the response object

One method I'd like to explore is using middleware functions to alter the response. app.use(function(request, response, next) { .. do something .. next(); // moves to next middleware }); When it comes to modifying the request and response ob ...

Error encountered in ASP page due to JavaScript syntax issue

<script type="text/javascript"> /* <![CDATA[ */ var on_id = 1; if (<%=GetValue() %>) { on_id = <%=GetValue() %>; } </script> I am encountering two syntax errors: one ...

CSS Navigation Bar Fails to Function Properly on Mobile Devices

Check out the plunkr I have created by visiting: http://plnkr.co/edit/gqtFoQ4x2ONnn1BfRmI9?p=preview The menu on this plunkr functions correctly on a desktop or laptop, but it doesn't display properly on a mobile device. I suspect that the issue may ...

What is the process for removing a specific photo from a user's profile if the photo in question has a file beginning with file://?

How can I delete a specific photo object of the user if that photo object starts with file://? I am currently working on adding an image feature in my app using NodeJs. The route I have created for uploading images is functioning properly. However, I encou ...

JestJS: Async testing isn't halted

I am facing two issues with my jest test: Is there a way to define the Content collection only once instead of repeating it inside the test? I encountered this error: Jest did not exit one second after the test run has completed. This usually indicates ...