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

`What purpose does the data-view attribute serve in Durandal JS?`

While experimenting with the Durandal JS starter kit application, I happened to view the page source in Mozilla browser and noticed the following. <div class="" data-view="views/shell" style="" data-active-view="true"> </div> I couldn't ...

Events are not being emitted by Socket.io

I recently started learning about socket.io and began following a tutorial on the socket.io website. I have installed everything correctly, but it seems that the socket is unable to emit the event in the index.html file. Can anyone help me with this? Here ...

Using ng-repeat in AngularJS to display Google charts

I am a newcomer to AngularJs and Google charts. My goal is to dynamically display Google charts in an ng-repeat for each list item. <li ng-repeat="ques in surveyquestions"> <label for="{{ques['questions']}}"> {{ques[&apos ...

instructions on how to exclusively close a bracket within a double bracket in a regular expression match

const input = "example(1)(2)example(3)example(4)(5)example(6)(7)example(8)example(9)" const regexp = new RegExp(????) // <-- need help with this input.match(regexp) result: [example(1)(2), example(3), example(4)(5), example(6)(7), example(8), example( ...

Exploring the `React.createRef` method using Enzyme for testing purposes

Is there a way to test the following class that utilizes the React.createRef API? I couldn't find any examples online. Has anyone attempted this before? How can I mock the ref effectively? My preference would be to utilize shallow. class Main exten ...

Create a basic chart using JavaScript

I am looking to replicate a specific chart using JavaScript. The red point in the chart is variable. So far, I have attempted to create it using the flot library: var d3 = [[7,7]]; $.plot("#placeholder", [{ data: d3, points: { show: true } }], { ...

Struggling to capture a "moment in time" of a form without losing any of the data

My form is highly dynamic, with interacting top-level elements triggering a complete transformation of the lower-level elements. I needed a method to maintain state so that if users partially entered data in one category, switched temporarily to another, a ...

employing flush for lodash's throttle wrapper

When using TypeScript with JavaScript and Angular: I am trying to use the throttle decorator from lodash to limit an API call while a user is navigating around the page, ensuring that it fires before they leave the site. In my TypeScript constructor, I h ...

React Big Calendar encountered an error: The element type provided is not valid, as it is expected to be a string for built-in

Error One: The element type is invalid: it was expecting a string (for built-in components) or a class/function (for composite components), but received undefined. This could be due to not exporting your component correctly from the file where it's d ...

Issue with SetTimeout not functioning properly on initial use within socket.io

Currently, I am trying to come up with a method to retrieve an IP address from a node server that is hosted on a dynamic IP. The issue I am facing is that the setTimeout function does not seem to work properly on the server side during the initial launch. ...

What is the process for turning off express logs on my node.js command line interface?

Recently, I've begun delving into the world of node.js and in an effort to improve my debugging practices, I've decided to move away from relying solely on console.log. Instead, I am exploring the use of debug("test message") for my debugging ...

Display the date string in Material-UI TableCell格式

I have a TableCell component in Material-UI that displays dates in the format 2019-03-25T19:09:21Z: <TableCell align="left">{item.created_at}</TableCell> I want to change this to a more user-friendly format showing only the date as either 25/ ...

What is the most compatible JavaScript framework for openlayers?

I'm seeking guidance on selecting a front-end framework (e.g. React, Vue, Angular) that is compatible with OpenLayers for my upcoming implementation. Could you please recommend the most suitable front-end framework to work seamlessly with OpenLayers? ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

Ensure that ExpressJS response includes asynchronous try/catch handling for any errors thrown

Currently working with ExpressJS version 4.16.0, NodeJS version 10.15.0, along with KnexJS/Bookshelf, and encountering issues with error handling. While errors are successfully caught within my application, the problem arises when trying to retrieve the e ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

Utilizing AngularJS ngResource: Ensuring Consistent Use of the Catch Function

Each time a server request using any $resource fails, I want to display the same alert message to my users. Currently, my code looks like this: function tryAgain() { alert("try again") } myResource.query().$promise.catch(tryAgain); myResource.update(...) ...

Ways to create two separate references pointing to a single object

Here is the code I am currently running: function TypeOfCar(vehicle) { this.vehicle = vehicle; } var sedan = new TypeOfCar('sedan'); var carType = race; console.log(carType); console.log(sedan); After running the code, the output is as follo ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...