Shifting a portion of Controller logic to a Service in AngularJS

Here is some code you should consider:

HTML:

<!doctype html>
<html ng-app="todoApp">
    <head>
        ...
    </head>
    <body ng-controller="MainController as myControl">
        ...
    </body>
</html>

AngularJS Controller:

angular.module('todoApp', []).controller('MainController', function($scope, $http) {
    ...
});

If you want to move all the $http calls to a service instead of having them in the controller, I can show you how. Also, if you'd like to use ng-bind instead of location.reload(), I can explain that too.

Answer №1

Let's take an example where we create a factory called Users and include all User-related API functions inside it:

'use strict';

angular
    .module('todoListApp')
    .factory('Users', usersFactory);

    function usersFactory($http) {
        var service = {
            get: getUsers,
            //edit: edit ...
        };

        return service;

        function getUsers() {
            return $http({method : 'GET',url : 'http://localhost:8000/users'})
            .then(function(response) {
                return response.data;
            });

        }

        //function edit(user) {
        //    return $http({method : 'PUT...
        //}

    }

The next step is to inject this factory wherever you need to use it.

In your controller, you would essentially do the following:

angular.module('todoListApp', [])
    .controller('MainController', function($scope, Users) {

    //.....
    function loadUsers() {
        Users.get().then(function(data){
            thisApp.users = response.data;
        }, function() {
            alert("Error getting users");
        });
    }      

    loadUsers();
    //...

You can repeat this process by creating appropriate services for notes and projects as well.

To keep the main app.js file clean, move these services into separate files like users.service.js. I also recommend moving controllers into separate files too.

When attaching a service/factory/controller within a separate file to the module, remember to do this:

angular.module('todoListApp').anything

Additionally, instead of using location.reload to update the view with new data after editing or deleting a User, call loadUsers() in the then() section of those operations.

I hope this explanation makes sense!

PS: For more guidance on Angular development, consider checking out the styleguide by John Papas, which has been very helpful to me.

Answer №2

I have previously utilized a service factory solution to tackle a similar issue.

angular.module('data-service').factory('dataService', ['$http',function ($http) {
  var url = 'http://localhost:8000/';
  return {
    getData: function(type) {
      return $http({method : 'GET', url : url + type});
    },
    allData: function() {
      return $q.all({
        notes: this.getData('notes'),
        users: this.getData('users'),
        projects: this.getData('projects')
      });
    }
  }
}]);

Example of usage:

dataService.getData('notes').then(function (data) { ... });

You can also utilize Angular promise $q.

dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

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

How can I retrieve the access token from the Id_token using Azure AD Authentication Library (ADAL in angular 5)?

Within my Angular 5 project, I have incorporated the adal service for Microsoft auth2.0 authentication. When retrieving the id_token, I utilize this.adalService.getCachedToken(this.secretService.adalConfig.clientId); However, I require an Access Token to ...

Obtain the URL of the parent window from a modal dialog using JavaScript

What is the proper syntax for obtaining the URL (specifically, the PATH) of the parent window from a modal dialog box in Internet Explorer. I have attempted several variations such as: window.opener.document.location window.opener.location this.opener.do ...

what version of Node.js is required for Ionic V1.4.3

I prefer using Ionic V1.X for its compatibility with AngularJS that supports .js, compared to Angular with .ts support. However, when I attempt to check my Ionic version using "ionic -v," the output shows: ReferenceError: primordials is not defined at Mo ...

Receiving a 500 status code upon converting a SqlDataReader into Json format

Getting a status 500 error and not sure where I am going wrong. When I click on the 'Getcustomers' button, the 'GetCustomers' method is called which returns JSON. Script: <script> var MyApp = angular.module("MyApp", []); ...

Converting a JSON object that is created dynamically to XML in node.js

Is there a way to convert a dynamically created JSON object into XML using node.js? I am tasked with generating JSON objects dynamically based on available data, which includes nested lists of objects. var Obj = { root: { Door_Keeper: { ...

Having trouble with connect-busboy not calling the callback when using NodeJS, AngularJS, and File Upload?

Click here for the sources I am currently working on implementing a NodeJS server that allows file uploads using connect-busboy from AngularJS with the help of angular-file-upload for later analysis. The issue I'm encountering is that the callback f ...

Mastering the Art of Tallying Select Choices in Protractor

Experiencing an issue with counting options in the select attribute during my test. Here is the code snippet: it('should verify the number of options', function()) { expect(element(by.id('sorting_options')).all(by.tagName('optio ...

Prevent the query from being executed by halting the AJAX call

Within my web application, I have a specific button that triggers an AJAX call upon being clicked. On the server side, I need to run a query against a database. I am concerned about the execution time of these queries and worry that users may be impatient ...

Add a static line of names to a JavaScript file

Looking for a way to generate data with the following javascript snippet: for (var l = 0; l < table.length; l +=1) { fs.appendFile('results/Test'+ username +'.csv', var1+i, var2 , function(err) { if(err) { return c ...

Having trouble with identifying the largest number in an array using JavaScript

As I populate an array from input fields, I am faced with the task of finding the largest number in that array. Using Math.max(myData) results in a NaN error, and relying on an "if" statement sometimes gives correct results and sometimes doesn't. For ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

Exploring JavaScript and mastering it through Visual Studio Code and Node.js for debugging and learning

I am currently using Visual Studio Code to practice and test my Javascript skills. In order to activate debugging features, I have installed Node.js and selected "node" in the launch.json file. What's confusing me is that the outcome of my code seem ...

Arrange the column according to the property I am sending to a Cell

Header: "Votes", accessor: "Voter", filterable: false, Cell: row => <Voter id={row.index} vote={this.filterCount(row.index)} />, sortMethod: null //sort based on vote prop passed above ^ I am trying to sort my tabl ...

Automate the process of saving information to Google Sheets using Google AppScript

I have a Sheet named 'Automatic' where I've imported a set of data using IMPORTXML. My goal is to update this data list daily at the same time to create a database with various stock quotes over time. Is there a way to accomplish this usin ...

ShallowWrapper from Enzyme fails to pass props to a basic React component

I am currently working on a test for a straightforward React component that receives an object as props and displays text from that object on the screen. Below is the code I have written: QuoteBox.js import React from 'react' export default cla ...

The Angular 2 view appears on the screen before the data finishes loading in the ngOnInit

Utilizing the github API in my angular 2 application, I encounter an issue where the view renders before ngOnInit has finished loading data. This leads to a Cannot read property of undefined error. The relevant portion of my code is as follows: ngOnInit() ...

I attempted to implement an AJAX partial refresh for my HTML, but unfortunately, it did not have the

I've been attempting to implement Ajax to locally load the page, but unfortunately, the code below isn't functioning as expected. My intention is to transmit the 'MSG' information from 'views' to Ajax and refresh the page loca ...

Best practices for securely storing access tokens in React's memory

I'm on a quest to find a secure and efficient way to store my access token in a React application. First and foremost, I have ruled out using local storage. I don't see the need to persist the access token since I can easily refresh it when nece ...

Is there a PHP script available to verify the status of FTP servers and determine if

I am in need of creating a PHP script that is triggered by a setInterval("ajaxrequest('ftp.php', 'context')", 1000) function. The PHP script itself is quite simple. It consists of an array containing FTP addresses. The script loops thro ...

How can I apply a texture to a 3D rectangle in THREE.js?

I am attempting to create a 3D box in THREE.js that represents a box made up of 2x4 Legos, measuring 24 pieces wide by 48 pieces long and an unspecified number of pieces tall. I have created a texture displaying this pattern using random colors: https://i ...