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

The dropdown menu is not able to retrieve information from the secondary database

I have been encountering multiple challenges while working on a web-based dynamic form that I am developing. My current major issue is with populating the second #bodytype dropdown based on the selection made in the first, #bodyman, dropdown. Subsequently ...

Is it possible for a JWT generated using RS256 to be decoded on the jwt.io platform?

After setting up my first Express server and implementing user authentication with jwt, I'm now searching for a method to encrypt the jwt in order to prevent users from viewing the payload on the website. I am curious if anyone is aware of an encryp ...

Using Vanilla JavaScript and VueJS to smoothly scroll back to the top of a div when a button is clicked

I have a VueJS-based app that features a multistep form with a next button. You can check out the functioning of the app here: My current challenge is ensuring that once the user clicks the next button, the top of the following question becomes visible. I ...

I am seeking assistance with my code. It is passing most of the test cases, but is failing only two without any error messages. What could

I recently started teaching myself programming, so please excuse me if my question seems a bit basic. One of the challenges on CodeCamp requires defining a function that takes an array with 2 values as input and returns the Least Common Multiple (LCM) of ...

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

md-datepicker incorrect input- AngularJS

When selecting a non-existent date manually in the input, the calendar shows the date I expect but the input does not. Here is the code snippet: <md-datepicker name="startDate" class="custom-datepicker" ng-model="models.startDate" md-placeholder="Ente ...

Implementing a Vue feature where an object is utilized as the v-model within a select

I am currently working with a select tag that displays an array of objects as its options. Each option only shows the name property of the object. The v-model on the select tag is initially set to one of the object's name properties. My aim is to use ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing t ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Angular custom filter with FabricJS

I am working with a binary/grayscale image and my objective is to filter the image so that all white color becomes transparent and all dark colors change to a specific user-defined color. I am facing challenges in creating a custom filter in Angular. I ha ...

Unable to retrieve DOM value due to Vue.js template being inaccessible in Chromium, including from both DevTools and extensions

Currently, I’m developing a Chrome extension that needs to retrieve specific values from a webpage such as the item title. However, instead of fetching the actual title, it is reading a Vue.js template variable. Even when I use DevTools to inspect the p ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

The validation for the start and end dates in the datepicker is not functioning properly when

I have integrated a bootstrap date picker into my website. However, I am encountering an issue where the end date validation does not update when I change the start date after the initial selection. <script type="text/javascript" src="htt ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

Code error detected on basic webpage

I've been experimenting with my local storage and have encountered a strange issue. The code example that I had previously tested successfully is now not working, and I can't figure out what went wrong. Check out this link for additional informa ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

What is the most effective method for serializing SVG data from the client's Document Object Model (DOM

As I delve into the world of creating interactive SVG/AJAX interfaces, I find myself faced with a challenge. Users are constantly manipulating elements on-the-fly and I want to give them the option to export their current view as a PNG image or an SVG docu ...

Iterate through a JSON object using JavaScript, with distinct keys but the same object structure

Hello, I'm currently in the process of creating a slider using images sourced from a json file. Here is the json structure that I am working with: { "info":[ { "slide1":[ { "title" ...

Learn how to extract information from a JSON data array and seamlessly integrate it into an ObservableCollection using C# in Xamarin

Reviewing my JSON data { "found": 501, "posts": [ { "ID": 2500, "site_ID": 1, "date": "2014-09-26T15:58:23-10:00", "modified": "2014-09-26T15:58:23-10:00", "title": "DOD HQ Visitors Parking", "metadata": [ { "id": "15064", "key": "city", ...