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

Display animated GIFs in the popular 9Gag format

Is there a way to display a GIF file after clicking on a JPG file, similar to the functionality on 9Gag.com? I am currently using timthumb.php for displaying JPG images. https://code.google.com/p/timthumb/ Below is the code snippet: <div class="imag ...

Is there a way to ensure that clicking a link_to only opens a partial once?

These are the files I am working with: _comment.haml %div.comment{ :id => "comment-#{comment.id}" } %hr - if current_user && current_user.id == comment.user_id || current_user && current_user.id == reel_user = link_to " ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Connect jQuery's resizable controls

Check out this jSFiddle. I am attempting to add event handlers for resizing $('oWrapper_'+num). However, the resizing does not occur. This is because $('#oWrapper_'+num) has not been added to the dom at the time of execution, so the se ...

How can I set the value of scope on a click event in Angular?

I'm having trouble creating a toggle feature in my angular project. I can't figure out why it's not functioning properly. My expectation is that when the a-tag is clicked, the lower div should display. <div> ...

Maintain Open State of Toggle Drop Down Menu

Having an issue with the toggle down menu or list on my webpage. The problem is that the menu is constantly open (the #text_box) when the page loads. My intention was for it to be closed initially, and then open only when the user clicks on the 'Ope ...

Issue with VueJS where changes made to properties in the mounted hook do not properly trigger the

I'm working on a VueJS component that features a button with computed properties for its class and text. These properties change every time the button is clicked, updating smoothly with each interaction. However, I've encountered an issue when at ...

Support for h264 in Windows Media Player across various versions of Windows operating system

Are there specific versions of Windows that are capable of playing h264 videos with Windows Media Player installed by default? Is it feasible to determine this support using Javascript? We currently deliver MPEG-4 video files through Flash, but some users ...

Interactive hover text appears when you mouse over the SVG path

Does anyone know the simplest way to display sample text when hovering over an svg path? Below is my CSS code: <style> path:hover{ fill:yellow;stroke:blue; } .available { fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:1px;strok ...

Maximizing the worth of itemtype using jQuery: A guide

My goal is to include an 'itemtype' attribute in the body tag, body.page-body.ng-scope.device-lg(itemscope='', itemtype='') I attempted the following method $('body').add(itemtype='t1'); Unfortunately, ...

The parameters for Vue.js @change events are consistently returning as 0 whenever a file is uploaded by clicking on the picture

Check out my JSFiddle here:: https://jsfiddle.net/includephone/o9gpb1q8 I've encountered an issue involving the @change event on an input field. My goal is to create a carousel of images with 4 images per slide. Data Object Structure data: functio ...

Incorporating D3.js into Angular 6 for interactive click events

Currently working on building a visual representation of a tree/hierarchy data structure using d3.js v4 within an Angular environment. I've taken inspiration from this particular implementation https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5e ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

I am looking to implement a dropdown menu that appears after clicking on an image. Any suggestions on how to achieve this using

I've been experimenting with adding a dropdown class, but I'm feeling a bit lost on where to start. Here's a snippet of code that shows what I'd like to do to add a dropdown menu: <span id="dropdown-info" ng-init= "myVar='i ...

Troubleshooting Ng-Idle problem across multiple browser tabs

When the same application is used in multiple tabs, both applications utilize the same localstorage to store ngIdle.expiry. This can cause one application to extend the session of another. Is there a workaround available in the current version to address ...

What is the best method for arranging multiple images in a grid while keeping them within a specific maximum width and height?

I've been staring at this problem for a while now, attempting every possible solution to resize images and maintain aspect ratio, but none seem to work in my case. Here are two images that I manually resized so you can view them side by side: highly ...

Setting references to child components with VueRouter in Vue

I've written the following code snippet in my main.js file for my Vue web application: const routes = { name: "Main", path: "/main", redirect: "/main/home", component: MainComponent, children: [ { path: &quo ...

Guide on grabbing characters/words typed next to # or @ within a div element

Within a div element, I have enabled the contenteditable property. My goal is to capture any text input by the user after typing '#' or '@' until the spacebar key is pressed. This functionality will allow me to fetch suggestions from a ...

Create a left-aligned div that spans the entire width of the screen, adjusting its width based on the screen size and positioning it slightly

I have a parent container with two child elements inside. I want the first child to align to the left side and the second child to align to the right side, but not starting from the exact center point. They should be positioned slightly off-center by -100p ...

Why does my element appear to be a different color than expected?

I've developed a sleek wind map (check out for reference). Using a weighted interpolation every 10ms, I generate uVector and vVector data to calculate wind speed. Based on this speed, each point is assigned a specific color as outlined below. if (we ...