Exploring the concept of inheritance in JavaScript and Angular programming

Currently, I am working on a project called "hello world" and it involves two HTML pages named "configuration.html" and "add configuration.html". Each page has its own controller defined as follows:

angular.module('MissionControlApp').controller('ConfigController', ConfigController);

angular.module('MissionControlApp').controller('AddConfigController', AddConfigController);

Both controllers share some common properties, which are:

function ConfigController($routeParams, ConfigFactory, $window){
    var vm = this;
    vm.status;
    vm.projectId = $routeParams.projectId;
    vm.selectedProject;
    vm.configurations;
    vm.selectedConfig;
    vm.selectedRecords;
    vm.filteredConfig;
    vm.newFile;
    vm.fileWarningMsg = '';

vm.addFile = function(){
        var filePath = vm.newFile;
        var encodedUri = encodeURIComponent(filePath);
        vm.fileWarningMsg='';

        ConfigFactory
            .getByEncodedUri(encodedUri).then(function(response){
                var configFound = response.data;
                var configNames = '';
                var configMatched = false;
                if(response.status === 200 && configFound.length > 0){
                    //find an exact match from text search result
                    for(var i = 0; i < configFound.length; i++) {
                        var config = configFound[i];
                        for(var j=0; j<config.files.length; j++){
                            var file = config.files[j];
                            if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
                                configMatched = true;
                                configNames += ' [' + config.name + '] ';
                                break;
                            }
                        }
                    }
                }
                if(configMatched){
                    vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
                } else if(filePath.length > 0 && filePath.includes('.rvt')){
                    var file1 = { centralPath: filePath };
                    vm.selectedConfig.files.push(file1);
                    vm.newFile = '';
                } else{
                    vm.fileWarningMsg = 'Warning! Please enter a valid file.';
                }

            }, function(error){
                vm.status = 'Unable to get configuration data: ' + error.message;
            });

    };

I have noticed that AddConfigController requires the same functionality for addFile(), so I simply copied and pasted the code. However, being familiar with C#, I believe there could be a more efficient way to handle this by utilizing class inheritance and extending from the ConfigController. Can this be achieved in Javascript?

If this question seems basic or straightforward, I apologize as JavaScript is still somewhat of a mystery to me.

function AddConfigController($routeParams, ConfigFactory, $window){
    var vm = this;
    vm.status;
    vm.projectId = $routeParams.projectId;
    vm.selectedProject = {};
    vm.newConfig = {};
    vm.newFile;
    vm.fileWarningMsg = '';

vm.addFile = function(){
        var filePath = vm.newFile;
        var encodedUri = encodeURIComponent(filePath);
        vm.fileWarningMsg='';

        ConfigFactory
            .getByEncodedUri(encodedUri).then(function(response){
                var configFound = response.data;
                var configNames = '';
                var configMatched = false;
                if(response.status === 200 && configFound.length > 0){
                    //find an exact match from text search result
                    for(var i = 0; i < configFound.length; i++) {
                        var config = configFound[i];
                        for(var j=0; j<config.files.length; j++){
                            var file = config.files[j];
                            if(file.centralPath.toLowerCase() === filePath.toLowerCase()){
                                configMatched = true;
                                configNames += ' [' + config.name + '] ';
                                break;
                            }
                        }
                    }
                }
                if(configMatched){
                    vm.fileWarningMsg = 'Warning! File already exists in other configurations.\n' + configNames;
                } else if(filePath.length > 0 && filePath.includes('.rvt')){
                    var file1 = { centralPath: filePath };
                    vm.selectedConfig.files.push(file1);
                    vm.newFile = '';
                } else{
                    vm.fileWarningMsg = 'Warning! Please enter a valid file.';
                }

            }, function(error){
                vm.status = 'Unable to get configuration data: ' + error.message;
            });

    };

Answer №1

If you are working with ECMAScript 5 and seeking guidance on inheritance, consider exploring Object.create(). Delve into the classical inheritance example for further insight.

In the context of AngularJS, an optimal approach would involve creating a Service dedicated to managing files or configurations. Place the addFile function within this service to allow multiple controllers to access it by injecting the service. This facilitates sharing the same functionality across various components in the application.

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

Unable to add a new table in asp.net due to a preexisting table in the code first migration

In the process of developing an ASP.NET MVC website, I am utilizing Entity Framework with a code-first approach to interact with the database. However, I have encountered an issue when it comes to adding/migrating a new table and entity to my model and dat ...

Is there a javascript file storing an image?

Currently, I am in the process of creating my personal portfolio website and incorporating react-bootstrap for designing my react components. I have been attempting to add an image using the Image component provided by react-bootstrap. However, I noticed ...

What is the process for attaching a dynamically generated object to the document's readiness event?

One of my tasks involves dynamically generating a slider element using the code snippet below: function NewDiv(){ for (var count=0; count < parseFloat(sessvars.storey_count); count++) { var string="<br><div ...

Ways to display a vast amount of information on a dynamic grid view

I am facing a challenge with loading a large amount of data into a dynamic grid view, where link buttons are created dynamically based on the data. When clicking the link button, an inner grid should be loaded which is working correctly. However, every ti ...

TRPC fails to respond to the passed configuration or variables (e.g., when enabled is set to false)

Recently started using trpc and I'm trying to grasp how to utilize useQuery (which I've previously worked with in react-query): const IndexPage = () => { const { isLoading, data, isIdle } = trpc.useQuery([ "subscriber.add", { email: ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

Top method for handling chained ajax requests with jQuery

I'm facing a scenario where I have to make 5 ajax calls. The second call should only be made once the first call returns a response, the third call after the second completes, and so on for the fourth and fifth calls. There are two approaches that I ...

Problems with form functionality in React component using Material UI

Trying to set up a signup form for a web-app and encountering some issues. Using hooks in a function to render the signup page, which is routed from the login page. Currently, everything works fine when returning HTML directly from the function (signup), ...

The issue with fetching user profile data on the client-side in Next.js 14

I've run into a problem with client-side data fetching on my Next.js 14 project. More specifically, I'm trying to retrieve user profile information from a backend API using Axios within a component, but for some reason, the data isn't coming ...

One effective way to set up an array in an AngularJS application before the $scope is loaded is to

I'm currently experiencing an issue with my AngularJS application. Within the HTML view, I have a list containing JavaScript objects. <div ng-init="initWeek()" ng-controller="TableController"> <div id="TaskImages"> <div ng-repeat="task ...

Implement a JavaScript confirm dialog for a mailto hyperlink

Is there a way in javascript to automatically detect mailto links on the page and prompt a confirmation dialog when clicked by a user? I came across a method on this website for displaying an alert message. My knowledge of javascript is very basic. It&ap ...

The Node.js application is unable to locate the source file path

Currently, I am in the process of creating a simple quiz application. While working on this project, I encountered an issue with linking a JS file in an HTML template. Even though I have confirmed that the path is correct, every time I run my node app, the ...

Rendering HTML or links sourced from encoded JSON data with JavaScript

After making an ajax call, I receive the following data: {"dataList":[{"date":"August 27, 2013","text":"<a href=\"http:\/\/www.example.com\/test.aif\" title=\"Click here to listen\" target=\"\">Click her ...

Error encountered: Index 109 - The function $.ajax(...).success is not recognized as a valid function while working with jQuery in a Node

I'm just starting to learn about jquery and have been experimenting with ajax in my recent code. Below is the snippet of what I have implemented: $(function(){ $("#status").change(function(){ if($(this).is(':checked')) ...

What method sits snugly between prepend() and append()?

Just a quick question I have. I am attempting to align an element with my target. Usually, we use prepend (before the target) and append (after the target). Is there something similar that allows us to position that element directly on top of what we are ...

Learn how to properly register the order of checkboxes in AngularJS

I have a unique requirement for my webapp where I need to display the order in which checkboxes are checked. I came up with the following code to achieve this functionality: $scope.updateNumbers = function(id, checked, inputs) { if (checked === true) ...

Is there a way to enable data-add-back-btn using jQuery script?

Currently, I am utilizing jQuery 1.9.1 and jQuery Mobile 1.3.1 to define multiple pages within my project setup: <div id="q1" data-role="page" data-add-back-btn="false" data-back-btn-text="Home"> <div data-role="header" data-position="fixed" ...

jQuery: Implementing a function for all elements, including those dynamically loaded through Ajax later on

I have implemented a jQuery function to resize text areas, but I need it to work on all text areas. The function works well for existing text areas: $(document.ready(function(){$("text_area").resizer('250px')}); However, it fails to resize tex ...

Arranging data using jqGrid's Inline Editing Feature

Can the data on jqGrid be sorted directly on the client side while using inline editing? It appears that the data is not being sorted when the row is editable, even if the row header is clicked. ...

When using ng-repeat, make sure to track by $index for unique

After manipulating an array with 5 values (1, 2, 3, 4, 5), it now contains duplicate data (1, 2, 3, 4, 5, 1, 2, 3, 4, 5). I would like to use ng-repeat with $index to display the data without duplicates. Is this possible? ...