The architecture of Angular controllers

Being a novice in AngularJs, I have a query regarding the controller structure.

This particular file is my employeeController.js

    (function()
    {
        angular.module('employeeApp').controller('employeeController', employeeController);

        function employeeController(employeeFactory,$routeParams,departmentFactory,schoolFactory,mentorFactory,constants,$location,$scope) {
            var vm = this;
            // other code here...
        }

In my angular controller file, I have included two methods called editEmployee and createEmployee at the end of the file. I use these methods on both the 'create employee' page and the 'edit employee' page to load combobox values. For instance, on the 'create employee' page, I call

ng-init="employeeController.createEmployee()"
to populate those comboboxes.

Realizing that this may not be the most efficient way to handle this task, I am seeking suggestions on how to improve this process?

Answer №1

When structuring your app, the Angular team recommends following the style guide maintained by John Papa. You can find the Angular Style Guide by John Papa for reference.

One important suggestion is to separate the functionalities like create, show, edit, and delete into individual controllers. This approach aligns with the concept of Single Responsibility and Separation of Concerns.

If you are using the controllerAs syntax, there's no need to inject scope into your controller.

Below is an example code snippet for creating an employee (similar to create-employee.controller.js):

(function () {
  'use strict';
   angular.module('employeeApp').controller('CreateEmployeeController', CreateEmployeeController);
  
/** @ngInject **/
function CreateEmployeeController(constants, departmentFactory, employeeFactory, $location, mentorFactory, schoolFactory) {
var vm = this;
vm.create = create;
getMentors();
getSchools();
getDepartments();
getInternEducators();

function getMentors() {
  return mentorFactory.overview(constants.companyid).then(function (response) {
    vm.mentors = response;
  });
}

function getSchools() {
  return schoolFactory.overview(constants.companyid).then(function (response) {
    if (angular.isDefined(response[0].SchoolId)) {
      vm.schools = response;
    }
    else {
      console.log('empty!');
    }
  });
}

function getDepartments() {
  return departmentFactory.overview(constants.companyid).then(function (response) {
    vm.departments = response;
  });
}

function getInternEducators() {
  return employeeFactory.overviewInternEducators(constants.companyid).then(function (response) {
    vm.internEducators = response;
  });
}
}

function create() {
return employeeFactory.create(vm.employee, vm.profilePicture).success(function (response, status) {
  if (status == 200) {
    $.toaster({message: 'Employee added successfully'});
    $location.path('/home');
  }
}).error(function (response) {
  var i = 0;
  vm.error = response;

  angular.forEach(response.result.message, function (error) {
    if (i <= 2) {
      $.toaster({priority: 'danger', message: error});
    }
    i++;
  });
});
}
})();

You can create other controllers by splitting their functionalities in a similar manner as shown above.

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

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

What is the best way to create dynamic transparency based on cursor position?

Is there a way to create an animation like the one on https://meetwalter.com, where the transparency changes with the cursor's position? I previously attempted a similar implementation using CSS, but it seems that the website accomplishes this effect ...

"When attempting to pass a string into the res.send() method in Node.js, undefined

As a new Node.js user, I'm attempting to send data back to the browser by utilizing a function called load_blocks() from an external file that I created, and then calling it with res.send(). I currently have two basic files in my setup: The first on ...

Why does JSON remain unchanged when a value is explicitly assigned in Javascript

Why isn't my JSON structure updating when I explicitly assign a new value? items[0][i]['human_addressItem'] = address; I am trying to reverse geocode the latitude and longitude to obtain the human address, which is working fine. However, I ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Button for navigating to the previous slide on a Jquery slider

There appears to be an issue with the code on the previous button. When the user presses "previous" on the first slide, there is a momentary blank slider before the last slide appears. Is there a way to make this transition smoother? Thank you for your a ...

directive does not execute when the <Enter> key is pressed

I recently came across a helpful post on Stack Overflow about creating an Enter keypress directive. After following the instructions, here is my JavaScript code that replicates the functionality: JavaScript var app = angular.module('myApp', [] ...

Leveraging useContext to alter the state of a React component

import { createContext, useState } from "react"; import React from "react"; import axios from "axios"; import { useContext } from "react"; import { useState } from "react"; import PermIdentityOutlinedIcon f ...

Struggling with Vue's Router Transition fade in/out effect not functioning as expected?

Question: I've implemented Vue's Router and it switches between components without any issues. However, I added a <transition name="fade" mode="out=in"> around it but the fade effect is not working as expected. Desired ...

I am in the process of creating several checkboxes and am looking to incorporate some added functionality

Currently, I am working on a project that involves creating multiple checkboxes. My goal is to implement a specific functionality where only one checkbox can be checked in each group with the correct or incorrect value. Once all groups have been selected, ...

The check-all checkbox does not alter the properties of the selected object

Visit My Code on Plunker I'm attempting to update the statuses of all my list objects using a master checkbox that toggles all objects and updates their properties as per the chosen status from the select element. However, I've encountered an i ...

What is the best way to assign a unique number to every div id that is generated?

I am currently using a django for loop to retrieve data from a query set. As the information is displayed, I would like to have each item wrapped in a div tag with a unique id that increments by 1 for every instance. Is there a way to achieve this directly ...

Looking for assistance in establishing a connection between Node.js and Angular.js

I have a decent understanding of mongodb and node.js, but I'm struggling with angular.js. I need some help in figuring out how to retrieve data from my node.js code using angular.js. If there are any errors in my node.js code, please let me know. var ...

What is the best way to use jQuery AJAX to make changes to an HTML element that will be permanent even after the page is refreshed?

Starting out with codeigniter, I am working on building an ecommerce website. Every time a user clicks the "Add to cart" button in my view, I utilize jquery ajax to send a request to a controller function. This function then returns two variables: count ( ...

Issue encountered with AJAX multiple image uploader

I'm attempting to create an PHP and JavaScript (jQuery using $.ajax) image uploader. HTML: <form method="post" action="php/inc.upload.php" id="upload-form" enctype="multipart/form-data"> <input type="file" id="file-input" name="file[]" a ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

Is there a way to use jQuery to eliminate divs that contain multiple identical data values?

Is there a way to accomplish this? <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="14-March-2016" ...

What are the steps to create an endless scrolling feature?

I'm trying to create a slider with a horizontal scrolling effect, but I've hit a roadblock. How can I make the slider scroll infinitely? In my code, you can see that after Item 6, it stops scrolling and I have to scroll backward. However, I want ...

How can I utilize ng-repeat in AngularJS to iterate through an array of objects containing nested arrays within a field?

Here is the structure of an array I am working with: 0: {ID: null, name: "test", city: "Austin", UserColors: [{color: "blue"},{hobby:"beach"} ... ]} }... I am currently attempting to ng-repeat over this initial array in my code. However, when I tr ...

Using React to dynamically assign a backgroundImage based on a JSON response

I am having an issue with retrieving data from my Wordpress API and displaying it in my react app. Specifically, I am struggling to set the post's featured image as a background-image for an element. Here is an example of the JSON response: { "id" ...