Initializing controller variables in AngularJS

Within most of my controllers, I am utilizing an initialization function called init() to set up controller-specific variables. Although this seems like a common practice, I have been unable to find any documentation supporting it. The options that I currently see available are:

  1. Keep things as they are
  2. Switch to using the run or provider service

    (function () {
    
    'use strict';
    
    CompanyController.$inject = ['CompanyFactory','LocationService'];
    function CompanyController(CompanyFactory,LocationService) {
    
        let vm = this;
    
          // Initialization function  
        function init() {
            vm.company = {
                solutions: CompanyFactory.getSolutions(),
            };
            // Set $location 
            LocationService.setLocation('company-page');
        }
    
        init();
    
    }
    
    angular.module('app.company', [])
        .controller('CompanyController', CompanyController)
    
    
    })();                          
    

Answer №1

AngularJS 1.5 introduced controller lifecycle hooks, with the $onInit hook playing a crucial role:

this.$onInit = function () { ... }

The $onInit hook serves as a replacement for the pre-link function and is executed by the compiler. However, it may not be triggered if the controller is not associated with a directive (even ng-controller is considered a directive), such as when instantiated directly with $controller, like in a route controller scenario. In such cases, this.$onInit() must be explicitly called in the constructor.

It's important to note that the presence of function init() {...} in the original snippet is insignificant since it is not exposed as a method, meaning it does not contribute to the testability or extensibility of the controller.

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

Alter the border color of a bootstrap-div using JavaScript

I need to update the border color of a div element, but I'm encountering issues when using a bootstrap class on the div. Is there a way to change the border color using Javascript? <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/ ...

Bootstrap wysiwyg5 editor validation: Ensuring accuracy in your content creation

Currently, I have integrated the Bootstrap wysiwyg5 editor into a form. One of the fields in this form, specifically the text area, is mandatory and cannot be left empty. I am facing a challenge in validating whether the user has entered any content into t ...

After submitting the form, showcase the values in the textarea with each value on a new line for a

In my MVC, ASP.NET solution with angularjs integration, I have implemented a functionality where users can input values into a textarea and send them to a server. I am able to retrieve these values from the server and display them in the textarea using ng- ...

Alert: Ajax encountered an issue with the auto-refreshing field

When running a script I created for a self-updating field, I encountered the following error message: UpdateField.html:37 Uncaught ReferenceError: fieldname is not defined at HTMLInputElement.onchange (UpdateField.html:37) Script: https://i.sstatic.n ...

Exploring various endpoints using firestore Cloud Function

I am in the process of creating a versatile Cloud Function that can be executed on various endpoints. This is how my original Cloud Function looks: const functions = require('firebase-functions') const admin = require('firebase-admin' ...

I'm receiving identical results from findOne even when using different IDs

I am currently working on creating a new array of products based on a list of different Ids. However, I have encountered an issue where the same product is being returned for all Ids when using the findOne() method. let wishpro = ['632a5e5rtybdaaf ...

Having trouble with filtering JSON data in AngularJS?

I'm sorry if this question has already been answered. I tried looking for solutions on other websites, but couldn't understand them. I am attempting to filter JSON data within the ng-repeat function, but whenever I try to input something, it does ...

How to Handle 404 Errors for Specific Express Routes and Not Others

Struggling with the setup of a single page app using Angular routes on the front end, while facing backend issues. All database-related routes are functional, but any additional route designed to serve an HTML file or simple text like "hello world" result ...

Utilizing useEffect to dynamically update the state in useReducer

Currently in my application, I am integrating React Hooks/Context API. The task at hand is to transfer data fetched from localStorage and assign it to initialState.carts or state.carts when the Provider component mounts. However, there seems to be a limita ...

Tips for choosing a class using ng-if

Looking for a solution regarding my use of ng-repeat: HTML: <td class="border" data-ng-repeat="price in goHead.prices track by $index"> In the context of my <td>, I want to apply the class border if data-ng-if="price.isMinPrice" is true, oth ...

Master the art of navigating the Windows Sound Recorder with the power of JavaScript

I am creating a project that involves controlling the Windows sound recorder for tasks such as starting, stopping, and saving recordings. Is there a way to do this without displaying the recorder window? I would appreciate any assistance in solving this. ...

Why does my JavaScript code fail to retrieve input values?

When the button labeled click here is clicked, it will trigger an alert with empty values. I am curious why the alert does not display the values 400 and 400. This code snippet is from test1.php: <script src="https://ajax.googleapis.com/ajax/libs/jqu ...

Save user's email and password for future logins after the initial login

Is there a way to automatically populate the user's email and password in the login form when they check the "remember me" option and return to log in again? This is for a project using React and Next.js. ...

Attempting to upload information using AngularJS

https://i.sstatic.net/S4ZtU.jpg Hello there! I'm facing a challenge with Angular once again. Despite searching extensively on Google and in this forum, I haven't found a solution to my problem yet. Here's the issue: Currently, I have a loc ...

Redirect in Angular when there are no parameters in the URL

Whenever a user forgets their password, an email containing a URL is sent to their account. I am looking to create a page for resetting passwords that will only load if the URL has a specific parameter. My framework of choice is Angular. For instance: If ...

Creating an animated time-based scrollable bar chart in javascript

As someone who is new to JavaScript and charting, I am seeking assistance with a specific task. Despite browsing various JavaScript charting libraries and examples, none seem to address my issue: My goal is to generate dynamic stacked bar charts, as depic ...

Attempting to craft a multi-filter feature using AngularJS that will allow for the precise filtering of JSON data based on both month and year identifiers

I have integrated AngularJS into the RoR framework and am working on creating a multi-filter for the "ng-repeat" function to filter JSON data based on "month_id" and "year_id". Here is the current code: JSON: [ { "date":"October 4, ...

Tips for changing the dimensions of the canvas?

I'm struggling to display a photo captured from the webcam. The sizes are not matching up, and I can't pinpoint where the size is defined in the code. https://i.stack.imgur.com/Is921.png The camera view is on the left, while the photo should be ...

How to synchronize $scope variables between controllers in AngularJS

As a newcomer to Angular, I have a seemingly simple question regarding setting up a comments system for articles. I've implemented two angular controllers - one for loading comments upon page load and another for submitting new comments to the server. ...

Iterate through an array, mapping the values and then returning a

Look at the code provided: const { aForm, bForm, eForm, qForm, } = this.form; return ( aForm.isEditing || bForm.isEditing || eForm.isEditing || qForm.isEditing ); Can we optimize this in a different ...