What is the purpose of assigning controller variables to "this" in AngularJS?

Currently, I am analyzing an example in CodeSchool's "Staying Sharp with Angular" course in section 1.5. Here is the code snippet:

angular.module('NoteWrangler')
.controller('NotesIndexController', function($http) {
    var controller = this;
    $http({method: 'GET', url: '/notes'}).success(function(data){
        controller.notes = data;
    })
 });

I have gone through Mozilla's developer network guide related to [this][1], but my comprehension is still not optimal.

In the line from the above example:

var controller = this;

Why are we assigning controller = this? Why not simply declare var controller;? Is it because by equating it to this, we are making it a global variable rather than just a local one that would only be modified inside the success callback of the controller?

If needed, they later make use of the following in the HTML:

<div class="note-wrapper">
    <a class ="card-notes" ng-repeat="notes in indexController.notes">
    </a>
</div>

Answer №1

Why not simply declare var controller;?

The reason is that having just var controller; would result in controller being undefined.

var controller;
document.querySelector('pre').innerHTML = controller;
<pre></pre>

Is setting it equal to this turning it into a global variable?

No, you are not creating a global variable but rather a closed over variable. This allows you to utilize the value in your callback function. To access the value in a callback, you need to either create a closure variable or bind the function.

var controller = {
  hello: 'world'
};

// Example using a callback
setTimeout(function() {
  console.log(this);
}, 0);

// Utilizing a closure variable
setTimeout(function() {
  console.log(controller);
}, 0);

// Binding a function
setTimeout(function() {
  console.log(this);
}.bind(controller), 0);

Answer №2

Utilizing the this keyword to assign variables enables the addition of new namespaces when implementing the controllerAs pattern.

function FirstController() {
    this.message = "hello";
}

function SecondController() {
    this.message = "world";
}

HTML:

<div ng-controller="FirstCtrl as ctrl1">
    {{ctrl1.message}}
    <div ng-controller="SecondCtrl as ctrl2">
        {{ctrl2.message}}
    </div>
</div>

In the absence of utilizing controllerAs, resorting to using $parent is deemed undesirable. Imagine having to traverse through multiple levels like $parent.$parent.$parent.someData.

For more information, check out:

Answer №3

Is it necessary to set the value of this as a global variable in order to avoid just changing its own local controller variable in the success callback?

The behavior of this is determined by how a function is invoked.

Each new function call results in a unique value for this within that function.

By storing the value in another variable, the inner function can access and utilize it since it doesn't have direct access to the same this.

Although not technically considered global, it resides within a broader scope as a reusable variable.

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

Using ng-repeat within another ng-repeat allows elements to be displayed as siblings

My goal is to create a structured list using angularjs: Parent 1 Group1 Child1 Child2 Child3 Child4 Group2 Child1 Child2 Parent 2 Group1 Child1 Child2 Group2 Child1 I have data organized in a similar format like this. $scope.parents = [{ name:&apos ...

Utilizing regular expressions in Javascript to retrieve multiple instances

This paragraph contains a specific string txt = "Local residents o1__have called g__in o22__with reports..."; that requires extracting numbers between each occurrence of o and __ If we use the following regex: txt.match(/o([0-9]+)__/g); We will obtain ...

Setting a condition for a function call when a checkbox is clicked

My table has columns labeled NoBill and Bill, with checkboxes as the values. Here is the default view of the table: https://i.stack.imgur.com/ZUvb2.png When the checkbox in the NoBill column is clicked, the total value (this.total) is calculated. The t ...

Sort out videos for display based on a property in JSON using AngularJS

There are 4 buttons embedded in the HTML code. When any of these buttons is clicked, the videos should be filtered based on the "type" value found in the JSON data. Take a look at the code snippet below: <div class="btn-group hidden-xs" id = "selec ...

React Component that closes when it loses focus

In my React project, I am working on creating a custom select2 style component. Most of the functionality is complete, but I am struggling with figuring out how to hide the result box when the user clicks away. Here is the render method: render() { l ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Leveraging promises to make Ajax calls without repeating code

Would it be possible to create an ajax function without duplicating it? Passing different parameters, which are locations to various files. Then utilizing the promise to combine them into a single object, possibly incorporating the spread operator. Is th ...

New data field is created with AngularFire2 update instead of updating existing field

I am facing an issue with updating a Firestore model in Angular 6. The model consists of a profile name and a list of hashtags. The "name" is stored as the value of a document field, while the "hashtags" are stored as keys in an object. However, every time ...

Using HTML in jQuery or JavaScript: A Step-by-Step Guide

Here's the deal - I've got a bunch of buttons. What I want is, when the 4th button is clicked, to trigger a select menu option like this: The outcome I'm aiming for after clicking the button is I need some guidance on how to incorporate t ...

Discover the pixel width of a Bootstrap grid row or container using JavaScript

How can I calculate the width of a Bootstrap grid row or container in pixels using JavaScript? I am working with Aurelia for my JavaScript project, but I'm open to solutions in standard JS (no jQuery, please). Looking at the Bootstrap documentation, ...

Saving a Coordinated Universal Time and showcasing it in the corresponding local timezone

In my upcoming MVC4 application that will have a global audience, one of the features involves recording the date and time when a transaction is added or modified. Since I am storing the transaction datetime in UTC format, what would be the most effective ...

Ensure that the execution of the function is completed before moving on to the next iteration within a $.each loop

While I'm not an expert in JS or jQuery, I'm currently working on coding a chat application that requires the following functionality: Retrieve conversation list through an AJAX call Display the conversations on the left side of the webpage aft ...

What is the best way to access and process data from an $http request in a controller using a service

I am encountering an issue where the return value of the $http service in my controller is coming back as "undefined." Within my controller, I make a call to a service that utilizes $http: //this returns undefined vm.user_instruments = instruments.getIns ...

Select elements in jQuery using both a specific selector and a negative selector

I am currently working with a JQuery function that highlights a specific word and scrolls to it: $('article.node--article p, .video-title').highlightWordAndScroll({ words : search_word, tag : '<span class="found_key ...

Updating parent controllers in Angular 1.5 components via ngRoute

I'm currently utilizing ngRoute to develop an Angular single-page application and now I aim to transition to a component-based version. The challenge lies in isolated scopes. I require access to the main controller's properties and methods. Desp ...

What is the process for including an additional button in the DateTimePicker feature of material UI?

I'm currently utilizing DateTimePicker in my React application. I wish to incorporate a Clear button positioned to the left of the Cancel Button. import { MuiPickersUtilsProvider, DateTimePicker } from "@material-ui/pickers"; import DateFnsUtils fro ...

Navigate array in vue-chart.js

I've been utilizing Vue-chartjs with Laravel 5.7 for my project. The goal: I aim to pass an array to Vue so that I can dynamically generate a chart by looping through specific values. My approach so far: Here's the array I'm working with ...

Ensuring the canvas fits perfectly within its parent div

I am attempting to adjust my canvas to fit inside a div. // Make the Canvas Responsive window.onload = function(){ wih = window.innerHeight; wiw = window.innerWidth; } window.onresize = function(){ wih = window.innerHeight; wiw = window.innerWidth; } // ...

Error message thrown by a React custom hook: "Error: Queue is missing. This is probably a bug within React. Please report this issue."

In my React component, I need to utilize a custom React hook within the component. However, this hook should only be invoked when a specific feature toggle is enabled. I am aware that this approach may go against the rule of hooks as outlined here: https:/ ...