What is the process of instantiating controller components in AngularJS?

Here is an example of my controller in AngularJS.

angular.module('homePage').controller('buttonViewCtrl',  [function() {
    console.log(this);
    this.buttonDisplay = false;
    console.log(this);

    this.nav = function() {
        console.log(this);  
        this.buttonDisplay = true;
    };

    this.closeNav = function() {
        console.log(this); 
        this.buttonDisplay = false;
    };
}])

The first console.log statement logs an empty object initially.

The second console.log statement logs the controller object with a added property called buttonDisplay. https://i.sstatic.net/WMnla.png

The third console.log statement (inside nav()) logs the controller object along with all its methods: https://i.sstatic.net/dN9yb.png

The fourth console.log statement logs the same object with the updated buttonDisplay property.

https://i.sstatic.net/79dBj.png

I have some questions regarding this code snippet.

1) In this case, when the nav() method is executed, it seems that Angular automatically attaches all other controller methods to the controller object as well, even without them being triggered. This behavior is different from what I expected. Can you explain how Angular achieves this?

2) As per best practices in Angular development, it's recommended not to manipulate the DOM directly within controllers. In my case, the nav() function displays a navigation bar template and the closeNav() function hides it. Do you think this qualifies as DOM manipulation or am I incorporating too much presentation logic into the controller?

Answer №1

Upon analyzing this example, it appears that Angular simply acknowledges the presence of a controller definition by declaring an empty object.

Contrary to this belief, Angular does not actually instantiate the controller upon declaration. Instead, it waits until it is needed, such as when encountering a DOM node with the ng-controller="..." directive. Only then does it initialize the controller by calling new ControllerFunction(...) and passing in all declared dependencies as arguments.

The logic behind the first two console.log() calls running before the controller is fully initialized explains why some members may not be visible at that point.

Regarding Angular's best practices, manipulating the DOM within the controller is discouraged. However, if a function like nav() displays a navigation bar template or closeNav() closes it, is this considered DOM manipulation?

In this context, displaying necessary data for the view (template) is acceptable within a controller's scope. True DOM manipulation involves creating new elements, directly modifying attributes, implementing event handlers, etc., which should ideally be handled by directives instead.

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 is the best way to integrate gulp into an AngularJS project with a component-based folder structure?

Recently, I've been contemplating incorporating gulp into my development workflow. I came across an interesting article on the topic: The article outlines the use of a "seed structure". /app app.js /js /controllers loginController.js /parti ...

Retrieve the route parameters and exhibit the default option in a dropdown menu using Angular 2/4/5, along with translations implemented through ngx-translate

Is there a way to extract route parameters from a URL and then display them in a drop-down menu? I've attempted some solutions using ActivatedRoute, but they are not returning the first value after the base reference. For instance, If the URL is: l ...

What is the step-by-step process to upload a file along with JSON data using fetch and multer

My task involves uploading a file along with some metadata on a JSON object using the "fetch" JavaScript native function on the client side and Express with the multer middleware on the server side. Client Side: const formData = new FormData() formData.a ...

Tips for containing a moving element within the boundaries of its container div

I have a dynamic box placed inside another box, and I want to restrict its movement within the boundaries of the parent container. How can I achieve this? In simpler terms: I need the frog to stay within the frogger. HTML <div id="frogger"> ...

Utilizing Google Maps to display an infowindow upon clicking a location from a geojson file

I want to implement info windows that pop up when markers on a map are clicked. I used the sample code provided by Google (below) to create a marker map from geojson files dragged and dropped into the window. My goal is for the info windows to show text ta ...

Using Vue.js 2.x to Encode HTML Entities When Binding to v-bind:href

In my Vue application, I am using a v-for loop v-for="item in resultQuery" and outputting a link within this loop: <a v-bind:href="item.url"> <h2 class="title" v-html="item.title" v-bind:title="item.title"></h2> </a> In some cases, ...

Remove the innerHTML content of dynamically added elements using jQuery

After researching, it seems that event handlers are commonly added using methods such as .live(), .on(), .bind(), or .delegate(). My previous question may not have been clear, so I decided to delete it and ask a simpler one. Is there a way to clear the in ...

AngularJS Treeview - Rearranging tree nodes

My journey with Angular is just beginning, and I managed to create a treeview following this example: jsfiddle.net/eu81273/8LWUc/18/ The data structure I've adopted looks like this: treeview1 = [ { roleName: "User ...

Just diving into JavaScript, what makes jQuery so powerful?

As a newcomer to javascript (although functional programming is no problem for me), I find myself questioning some of the design choices made by jQuery. Is it too late to make changes now, or are they simply too ingrained in the framework? For example, the ...

`Problem encountered in establishing a database table through jQuery ajax`

I am completely new to utilizing jQuery and ajax. Currently, I am experimenting with creating a table on my local MySQL server using a JavaScript file that sends SQL statements to a .php file for execution. Here is the code in the .js file: function exec ...

The issue I'm facing is that the ng-click functionality in Angular JS is not functioning properly when the

Upon loading the page, my JavaScript function creates a tree structure from JSON data and generates a list of anchor tags which look like this: <a ng-click="shareParent(4619)">Some data</a> Despite associating the ng-click directive with the ...

Angular: Promise updating array but integer remains static

At the moment, I have a factory and a controller set up. The factory is responsible for updating with items retrieved from an endpoint along with the total number of pages of data. While my data array seems to be working properly, the pageCount (an integ ...

Encountered an issue during the npm install process for an Angular project

Below is the content of the package.json file: { "dependencies": { "@angular/animations": "^9.1.3", "@angular/cdk": "^11.1.1", "@angular/common": "^9.1.3", "@angul ...

Discover the color value within an array that begins with the "#" symbol

In my PHP code, I have written a function that extracts values from a CSS file and creates an array. Now, I need to loop through this array and create another array that only contains color values (strings starting with #). The challenge is that the length ...

How can I create an HTML link that opens a drop-down menu with form functionality?

Feeling a bit perplexed here as I'm not entirely sure how to label this issue... If you're familiar with the Facebook interface, I'm trying to develop a feature similar to the "DOWNWARD ARROW" icon found next to the "comments" or "status" b ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

What is the best way to trigger a re-render of an app following a mutation?

I am currently working on a React application using Next.js. One of the features I am trying to implement is the ability for users to log in and trigger a re-render of the app to fetch the current logged-in user. Within my _app.js component, I have wrappe ...

Show the results of fs.readdirSync() within an HTML file on the frontend

As someone who is just starting out with node.js, I've been searching online for a solution to the issue I've described in my question title. The project I'm working on involves creating a basic web API that allows users to upload their fil ...

Combining Client-side JavaScript with Django Rest Framework

Upon finishing the article on separating server and client architecture, I stumbled upon a question raised on Stack Overflow asking about separating REST JSON API server and client. This got me thinking if this dilemma also applies to Django. Is this dist ...

Is it possible for Javascript to manipulate the DOM of an Ajax text/html response?

My goal is to implement Ajax to retrieve an HTML page and extract a specific div by its ID, then insert that div into the current page. This involves loading a second page via Ajax, extracting the specified div from the response, and placing it within th ...