Divide the controller functionality from the factory operations in Angular

I'm looking to break up my code into smaller controllers instead of having everything in one large controller. However, I've come across this error:

Argument 'protocolController' is not a function, got undefined

I've created a factory for handling requests:

/*
    FACTORY THAT HANDLES ALL REQUESTS.
*/

function asyncFactory() {

    var factory = this;

    factory.list = [];

    this.update = function(restUrl) {
        return $http.get(restUrl)
        .success(function(data){
            factory.list = data;
        })
        .error(function(data){
            console.log('Error: ' + data);
        });
    };

    // Other functions like add, remove, and change...

}

And here's the controller that uses the factory:

/*
    PROTOCOL CONTROLLER
*/
function protocolController(asyncFactory){

    var controller = this;
    controller.list = asyncFactory.list;
    controller.formData = {};

    // Functions like getUpdatedList, addData, removeData, and editData...

}

To call it, use this approach:

/*
    MAIN - WHERE THE CONTROLLER AND FACTORY IS CALLED
*/
var app = angular.module('TransactionMonitoring', [])
.controller('protocolController', protocolController(asyncFactory));

Answer №1

Update :

/* MAIN - WHERE THE CONTROLLER AND FACTORY IS CALLED */

var app = angular.module('TransactionMonitoring', [])
.controller('protocolController', function(asyncFactory){

  var controller = this;
    controller.list = asyncFactory.list;
    controller.formData = {};

    this.getUpdatedList = function() {
        asyncFactory.update('../protocols')
        .then(function(data){
            controller.list = data;
        });
    };

    this.addData = function(formData){
        asyncFactory.add(formData, '../protocols');
    };

    this.removeData = function(value){
        asyncFactory.remove(value, '../protocols');
    };

    this.editData = function(value){
        asyncFactory.change(value, '../protocols')
    }
}


});

SERVICE:

app.service('asyncFactory',function ($http) {
 this.update = function(restUrl) {
        return $http.get(restUrl)
        .success(function(data){
            factory.list = data;
        })
        .error(function(data){
            console.log('Error: ' + data);
        });
    };

    this.add = function(formData, restUrl){
        $http.post(restUrl, JSON.stringify(formData))
        .success(function(data){
            console.log('Success: ' + data);
        })
        .error(function(data){
            console.log('Error: ' + data);
        });
    };

    this.remove = function(value, restUrl){
        // get index of clicked object
        var index = this.protocolList.indexOf(value);

        // Remove object with given index from array
        factory.list.splice(index, 1);

        var url = restUrl + value.id;

        // delete it from DB
        $http['delete'](url);

        console.log('Deleted object with ID ' + value.id);
    };

    // Change existing object
    this.change = function(value, restUrl) {

        // get index of clicked object
        var index = this.protocolList.indexOf(this.activeObject);

        var url = restURL + value.id + '/' + value.name;
        console.log('url: ' + url)
        // change it before store it to DB
        $http['put'](url);

        console.log('Changed object with ID ' + this.activeObject.id);

    };
}
}
)

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

Trouble with basic AJAX form submission

I have created a basic form and AJAX function to send the form data. However, the data is not being posted as expected. Can someone assist in identifying the issue? Fiddle: https://jsfiddle.net/onyeLp4d/2/ HTML <div id="lp-pom-form-25"> ...

The webpage becomes unresponsive and gets stuck when sending a stream of requests to the web server via ajax

I am currently working on creating a signal on the webpage that displays either a green or red color based on values retrieved from a database. However, when I send a request after 10 seconds, the page appears to freeze and becomes unresponsive. I am strug ...

Ways to conceal a div element when the JSON data does not contain a value

If the value in "desc" is empty, then hide <div24> and <popup-desc>. html <div class="popup"> <div class="popup-top" style="background-color: '+e.features[0].properties.fill+';"> ...

The AngularJS function invoked itself within the structure

When working with my form, I encountered a problem involving custom input directives and text fields. In addition to these elements, there are buttons: one for adding a new input to the form which is linked to the function $scope.AddNewItem() in the contro ...

Ways to implement a placeholder height for images on a webpage with varying heights using HTML

I'm facing an issue with an image on my website that has a dynamic width and height as defined by the following CSS: .sm_item_image { width:100%; height:auto; max-width:400px; } The problem arises when the image takes some time to load, ...

Can you explain the significance of the visitFunction error message?

When running [email protected] + [email protected] + [email protected] + [email protected], I encountered an error message. Can anyone help me understand what this error means? I am simply executing: res.render(view, response); Proper ...

creating a project using Yeoman

I'm attempting to create a project using Yeoman from a template. I am able to successfully copy all files from the Portanova template folder, but I encounter an error when trying to copy a file from another template folder and add it to my project. Th ...

What does the single-threaded nature of JavaScript signify in terms of its intricacies and ramifications?

As someone relatively new to Javascript and JQuery, I recently discovered that Javascript operates on a single-threaded model. This has left me wondering about the implications it carries: What should be taken into account when writing JavaScript code? Ar ...

Tips for halting the live graph plotting based on a specific condition with canvas js

I have a piece of code that generates a live graph based on probabilities. I am looking for a way to stop the plotting process as soon as a specific condition is met. <script> window.onload = function () { var dps = []; // dataPoints var c ...

Triggering JavaScript Function When Scrolling in Overflowed DIV

After using jQuery and searching for various ways to make this script work, I finally found a solution that works for my index.html file. <div style="overflow-y:scroll; height:300px"> <div style="background-color:black; height:500px"> </div ...

"Utilize JavaScript to extract data from JSON and dynamically generate a

I'm currently facing an issue with reading JSON data and populating it in my HTML table. The function to load the JSON data is not working as expected, although the data typing function is functioning properly. I have shared my complete HTML code alo ...

Creating a fade in or fade out effect in AJAX without using jQuery is a simple yet

Is there a simple way to achieve fade in or fade out effects in ajax without relying on jQuery? I'm looking for a solution that can add color or background color to make it visually appealing, especially for small web pages with poor internet connecti ...

Bootstrap 5 alert: The function `$(...).carousel` is not recognized

Despite browsing through numerous similar questions, none of the solutions seem to work for my issue. Listed below are some points I have checked: Jquery is loaded before bootstrap Bootstrap libraries are up to date Confirmation that bootstrap.min. ...

Identifying when two separate browser windows are both open on the same website

Is it possible to detect when a user has my website open in one tab, then opens it in another tab? If so, I want to show a warning on the newly opened tab. Currently, I am implementing a solution where I send a "keep alive" ajax call every second to the s ...

Can I substitute custom tags for the traditional <p> tag?

My HTML with CSS has an issue where a custom HTML tag is not displaying the text while my CSS picks up another tag. Interestingly, replacing <title>Layout Controls</title> with <p>Layout Controls</p> resolves the problem and shows t ...

Sticky Angular Headers

I am struggling to create a table on my angular page that has fixed headers and footers. <table class="table table-bordered table-striped table-hover" fixed-header> <thead> <tr> <th>Name</th> <t ...

The HTML button triggers a function to execute on a different webpage when clicked

I'm facing a straightforward issue that I can't seem to figure out due to my limited experience with Angular and web development. The problem revolves around two components, namely home and dashboard. In the home.component.html file, there's ...

What is the most effective way to configure a database for a project that will be utilized across multiple sub-domains, and what is the optimal

Embarking on the development of a large-scale web project meant to be utilized across multiple sub-domains representing different clients has me feeling lost. I am struggling to determine the best or most recommended solution for this type of undertaking. ...

Guide to obtaining context vnode within vue 3 custom directives

Unable to retrieve context from directive <template lang="pug"> div(class="form") select(name="name" v-model="form.input" v-select="form.inputs") option(v-for="(option, ke ...

What is the best way to extract the URL value and insert it into a text box?

After submitting the form, the URL looks like this: from=Paris%2C+France&to=Rome%2C+Italy On the new page, I need the value of 'from' to be inserted into the following input field: <input id="from" class="form-control" type="text" name= ...