Tips for eliminating redundant code in Angular controllers

I have a dilemma with two controllers that are responsible for similar tasks.

How can I efficiently eliminate code duplication?

Initially, my attempt was to create a template method as an angular service. However, I noticed that it's not possible to inject $scope into services.

.controller("TspController", function($scope, $rootScope, $routeParams, $location, ProblemsLoader) {
    $scope.problemType = "tsp";
    var problemId = $routeParams.problemId;

    ProblemsLoader.loadIndex("tsp", function(index) {
        if (problemId) {
            $scope.problems = index;
            ProblemsLoader.loadProblem("tsp", problemId, function(problem) {
                $scope.problem = problem
            });
        } else {
            var firstProblemId = index[0].fileName;
            $location.path("/tsp/" + firstProblemId)
        }
    });
})
.controller("VrpController", function($scope, $rootScope, $http, $routeParams, ProblemsLoader) {
    $scope.problemType = "vrp";
    var problemId = $routeParams.problemId;

    ProblemsLoader.loadIndex("vrp", function(index) {
        if (problemId) {
            $scope.problems = index;
            ProblemsLoader.loadProblem("vrp", problemId, function(problem) {
                $scope.problem = problem
            });
        } else {
            var firstProblemId = index[0].fileName;
            $location.path("/vrp/" + firstProblemId)
        }
    });
});

Answer №1

In this particular scenario, utilizing services proves to be an effective solution without the need to inject $scope.

With service exposing object properties, implicit watches are established, ensuring seamless propagation of state changes.

Service:

var issueService = function($http) {
    var issueData = {
        issueId: 1,
        issueField: '',
        otherIssueField: ''
    };

    return {
        issue: issueData, // exposing data as objects
        loadIssue: function(issueId) {
            // loading logic implemented here
            issueData.issueField = 'load data content';
            issueData.otherIssueField = 'additional data fetched from server or elsewhere';
        }
    }
}
angular.service('issueService', ['$http', issueService]);

Controllers consuming the service:

angular.controller('ctrl', ['$scope', 'issueService', function($scope, issueService) {
    $scope.issue = issueService.issue;
}]);

Changes in fields within the issue service will automatically reflect in any controller where the service is injected

<div>{{issue.issueField}}</div>

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

What benefits does the useCallback() hook offer in addressing function equality concerns within React?

Exploring useCallback() Hook In my quest to grasp the inner workings of the useCallback() hook in React and its significance in resolving function equality concerns, I came across a blog post shedding light on the topic. However, there are still some aspe ...

Encountering an issue where properties of undefined cannot be read (specifically 'img') following an update to the img value using redux toolkit

Hello! I have a project built with MERN and redux-toolkit (using an older version as per the tutorial). On the product page, I am trying to update a selected product. The update route runs without any errors, but after updating, I encounter an error that s ...

Webpack is causing issues with Angular Component Service Injection

Challenging Situation An issue has arisen where I am experiencing problems with Angular's Dependency Injection (DI) system. It appears that the DI only functions properly if I utilize the @Inject decorator within the constructor of a component when i ...

Load Jquery hover images before the users' interactions

Currently, I am in the process of creating a map of the United States. When hovering over any specific state, my goal is to replace the image with one of a different color. The issue I am encountering lies in the fact that the image gets replaced and a ne ...

Sending a JSON object back to HTML

In the process of developing a web app, I encountered a need to update the configuration of a specific graph type. My current approach involves utilizing Python3 with Flask and HTML. My objective is to achieve dynamic configuration updates without relying ...

Content moves as you scroll, not within a lightbox

I have implemented lightbox style overlays for my 'Read More' content on my website. However, I am facing an issue where the content within the lightbox does not scroll; instead, the background page scrolls. Any assistance with resolving this p ...

What is the best way to utilize JQuery AJAX to send XML data for a delete request?

I am having trouble sending XML type data to the backend using jQuery and AJAX as a DELETE request. When I do this, I receive an empty array from the backend's request body. How can I properly send the ID? Below is the code I am using: function delet ...

Resolving the clash between LookAt and controls within three.js

I am in the process of developing an application that showcases a 3D model of a building, and so far it's functioning well. I attempted to manipulate the "PerspectiveCamera" using LookAt, but I discovered that LookAt does not function properly when I ...

AngularJS - Bootstrap Datepicker with custom format 'mm-yyyy' still permits users to input date in 'mm-yy' format

After incorporating the bootstrap datepicker into an angular directive and applying it to a textbox, everything appears to be functioning correctly except for the validation aspect. Although I have configured it to only accept dates in 'mm-yyyy' ...

What can we expect from the behavior of a localhost Express app with an Aurelia/Angular Admin Panel?

Currently, I am working on a Web Project that utilizes Express to serve the website and an Aurelia (or any Framework) App as an Admin Panel for editing the content. The Aurelia-App is being served through the static/public directory of Express, with the co ...

Struggling to update the position of an array and dynamically show its contents using Angular

I am working with an Array of Objects, each containing an Array of strings. Utilizing ng-repeat to display all the strings, I have a button to switch to the next set of strings by changing the selected object in the outermost array. Below is the code snipp ...

express-validator never accepts valid input

Currently, I am working on a project using the most recent version of nodejs and express. The basic site setup is complete, and now I am focusing on implementing user authentication based on what I've learned from this course. However, no matter what ...

retrieving XML information through DOM children elements

Suppose I have an XML object in the following format: <book id="01"> <author>Conner, Jim</author> <title>House Hunter</title> <genre>DIY</genre> <price>5.95</price> <publish_date>2000-1 ...

I am encountering the error message "The property 'ɵmod' is not found in Type Storage" within IONIC

Currently facing an issue while trying to launch my ionic project. The error message reads "core.js:1023 Uncaught Error: Type Storage does not have 'ɵmod' property". Despite my attempts to resolve this error, I have not been successful. Any sugg ...

Beginner in Angular: Resolving Typescript Error "All instances of 'imageLoader' must have the same type parameters"

Struggling to grasp the basics of Angular 2 has been quite a challenge for me. After learning that script tags can only be used in index.html, I decided to try and convert one of my js files to ts within the component class of app.component.ts. Any help or ...

Utilizing request parameters within middleware that employs the 'createHandler' function from the 'graphql-http' package

I'm currently working on an Express server that uses GraphQL to handle HTTP requests. One of the key features of this Express server is the implementation of two crucial middlewares: app.use(authenticate); app.use('/graphql', createHandler ...

Tips for eliminating index.html from URL in a website driven by AngularJS

Is there a way to clean up the URL by removing index.html and making it clearer for users? mydomain.com/index.html#/myview1 mydomain.com/index.html#/myview2 I want the URL to look like this: mydomain.com/myview1 mydomain.com/myview2 Thank you in advan ...

How to set a background image with vue.js

My website design requires 70% of the page to be covered with an image, but the image is currently blank. I am using Vue.js as my frontend framework. Below is the code snippet that is resulting in a blank space: <script setup lang="ts"> imp ...

Having difficulty accessing a specific route on Stormpath while logged in

Currently, I am delving into the realm of using stormpath alongside express. Within my fullstack angular/node project that was created through yeoman with the angular-fullstack generator, I have successfully implemented login, register, and forgot password ...

What is the process for turning off a TypeScript rule for a single line of code?

Dealing with Summernote as a jQuery plugin has been a bit of a struggle for me. I'm trying to modify the object without needing type definitions, but TypeScript keeps throwing errors my way. Even after attempting to delete certain keys, I still get th ...