Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance:

(function () {
  'use strict';

  angular.module("Dashboard")
  .controller("DashboardController", DashboardController);

  DashboardController.$inject = ["Interface"];

  function DashboardController (Interface)
  {
    var vm = this;

    /**
     * Total Open Tickets
     */
    Interface.openTickets().then(function (data) {
        vm.tickets = objCount(data);
      });
  }

})();

I always display the total open tickets in my view, so there hasn't been a need for an additional method. However, I'm considering whether it would be more beneficial to make a separate method for the Interface call and then initialize all methods like this:

function DashboardController (Interface)
{
  var vm = this;
  vm.getTickets = getTickets();

  /**
   * Total Open Tickets
   */
  function getTickets() {
    Interface.openTickets().then(function (data) {
        vm.tickets = objCount(data);
      });
  }

}

I believe the second example is more organized and cleaner, so I am contemplating updating all of my code. Do you think this approach is correct?

Answer №1

In my opinion, this is the most efficient way to write the code. Personal preferences play a significant role in determining the approach to take. I suggest avoiding a self-invoking function as it can make the code more cluttered. Using angular.module helps prevent the introduction of global variables. It's advisable to steer clear of C-style brackets due to potential issues with automatic semicolon insertion in JavaScript. Although I can't recall the specific example, Crockford addresses this in "Javascript, the good parts". If getTickets is only used to call another function, consider commenting on its purpose instead of including unnecessary code.

angular.module("Dashboard")
  .controller("DashboardController", function DashboardController (Interface) {
    var vm = this;

    /**
     * Get Total Open Tickets
     */
    Interface.openTickets().then(function (data) {
        vm.tickets = objCount(data);
      });
  });

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

iOS Chrome: Enabling Cookies with "Always Allow"

While the Safari browser on OSX has a setting under Privacy & Security -> Block Cookies -> Always Allow, enabling the storage of entries in the browser's local storage even when accessing pages from third party sites like those running in an iframe, I ...

Leveraging the power of node pkg to generate standalone executables while configuring npm

I have successfully used pkg to create an executable file for my node js application. Everything is working fine in that aspect. However, I am also utilizing the config module to load yaml configuration files based on the environment. During the packaging ...

Is there a way to prevent the omission of zeros at the end in JavaScript when using Number.toString(2)?

I am facing an issue while trying to reverse a 32-bit unsigned integer by converting it to a string first. The toString(2) function is causing the zeros at the end to be omitted, leading to incorrect output. This is my code: var reverseBits = function(n) ...

Spreading angular attribute directives while compiling element directives

I am facing challenges in writing a custom element directive. This directive, which I'll name myElement, generates multiple textarea or input fields based on certain parameters and applies ngModels to those fields. In addition, I want to be able to s ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Challenges faced while working with Angular JS

Being new to Angular as a UI developer, I find myself struggling with a task at my new job. The company uses Angular JS with JAVA, and I am trying to add a new column to a table on an .html page. Despite my efforts in columns_panel.js, the new column is no ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

A guide on choosing a custom button color and automatically reverting to its original color when another button is clicked

I have a collection of 24 buttons, all in a dark grey (#333333) shade. Whenever I click on one of the buttons, it changes to a vibrant blue color (#0099ff), which is functioning correctly. However, when I proceed to click on another button, the previous ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...

Incorporate new content into JavaScript using the input element

I have a unique question - can text be added to JavaScript using the input tag? For example, <input type="text" id="example" /> And let's assume the JavaScript function is: function display_text() { alert("The text entered in #example wi ...

How can an Angular 2 component detect a change in the URL?

My Angular 2 component subscribes to a service based on the URL hash without calling any subcomponents. I am wondering if I should use Route or Location for this scenario, and how can I listen for and react to a pop state event? ...

Update the CSS for InputLabel

I have a drop-down list that I want to customize. The issue is illustrated below: I'm looking to center the text "choose format" within the field and adjust the font size. return ( <FormControl sx={{ m: 1, minWidth: 150 }} size="sm ...

Change the class of each item in a list individually by hovering over them with the mouse using JavaScript

How to toggle classes in a list item one by one using the mouseover event in JavaScript? const items = document.querySelectorAll("ul li"); let currentItem; for (const item of items) { item.addEventListener("mouseover", e => { currentItem &am ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Develop a plugin architecture using JavaScript and Node.js

Here is a basic implementation using node.js with express: var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello World'); }); app.listen(3000); I am interested in creatin ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Changing values in a select with multiple directives in AngularJs

Currently, I am developing a font selector directive using angularjs for an Umbraco property editor. Within the directive, there is a select element containing various fonts that are linked to the isolated scope. A peculiar issue arises when two directiv ...

Error: The function was expecting a mapDiv with the type of Element, but instead undefined was passed - google

I have a map within a div tagged with #mapa. Whenever I try to plot a route on the map, it refreshes. I don't want the map to refresh, and here is the code I currently have: <div style="height: 500px; width: auto;" #mapa> <google-map heigh ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

How can one retrieve data from two distinct API routes within a Next.js application?

Currently, I am working with Next.js and facing a challenge in fetching data from two different API routes simultaneously. My intention is to retrieve this data within the getServerSideProps function. The first dataset that I require can be found at the e ...