The significance of 'this' in an Angular controller

Forgive me for what may seem like a silly question, but I believe it will help clarify my understanding.

Let's dive into JavaScript:

  var firstName = "Peter",
    lastName = "Ally";

    function showFullName () {
    // The "this" inside this function refers to the window object
    // since showFullName() is in the global scope, just like firstName and lastName
    console.log (this.firstName + " " + this.lastName);
    }

    var person = {
    firstName   :"Penelope",
    lastName    :"Barrymore",
    showFullName:function () {
    // The "this" below points to the person object, as shown by person invoking the function.
    console.log (this.firstName + " " + this.lastName);
    }
    }

    showFullName(); // Peter Ally​
​
    window.showFullName(); // Peter Ally​

This makes sense to me. Now, transitioning to an Angular controller:

<script>
var app = angular.module("myApp", []);
console.log("Before Controller",this);
app.controller("myCtrl", function($scope) {
    console.log(this);
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    this.myTestFunction = function(){
        return this;
    }

    console.log("In test function ",this.myTestFunction());
});
</script>

Shouldn't the second line still log window because the controller function is in the global scope (I think)?

However, it returns an Object. Why?

Can I use this.myTestFunction without using ControllerAs syntax? What sets them apart?

Why does the last line also log object (in myTestFunction) when I am simply returning this from within?

I'm a bit confused about all of this. Could someone break it down simply?

Before Controller Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
VM2143 tryit.asp?filename=try_ng_module:5 Object {}
VM2408 tryit.asp?filename=try_ng_module:12 In test function  Object {myTestFunction: function}

Answer №1

When the last console log displays object object, it means you are attempting to concatenate an object with a string. To resolve this, remove the string and only show the function response.

console.log(this.myTestFunction());

Regarding the second question, you cannot access this.myTestFunction in HTML without utilizing the controller as a function. Without it, Angular can only recognize the scope functions within the controller.

var app = angular.module("myApp", []);
console.log("Before Controller",this);
app.controller("myCtrl", function($scope) {
    console.log(this);
    $scope.firstName = "John";
    $scope.lastName = "Doe";
    this.myTestFunction = function(){
        return this;
    }

    console.log("In test function ",this.myTestFunction());
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
 
</div>

Answer №2

Why does the second line still log window right when the controller function is defined in the global scope? However, it returns an Object. What is the reason for this?

In AngularJs Controllers, Services, Factories, etc., the this keyword refers to your controller/module itself. When a Module Constructor is called, this represents the module itself. In essence, this on a Controller is an Object that contains all of the controller's functions and variables. If a Controller named MyController is associated with a view MyView.html, then only that specific view can access MyController's variables and functions.

Can I use this.myTestFunction without using ControllerAs syntax? What is the difference between the two?

No, you cannot use this without utilizing the ControllerAs syntax. For example:

angular.module('myApp')
       .controller('MyController', MyController);

function MyController(){
   var vm = this;
   vm.hello = 'Hello There!';
}

And

<body ng-controller="MyController as myCtrl">
  <p>{{myCtrl.hello}}</p>
</body>

It will display Hello There!.

Why does the last line also log object (In myTestFunction) even though I am simply returning this from within?

This occurs because, as mentioned earlier, this is an object that contains all the variables and functions created inside the controller itself.

Additional Info:

It is recommended to use this instead of $scope within your controller. One of the reasons for this is that when you define a function using this, you can be sure that this specific function is accessible to a given view or module. Check out Angular Style Guide by John Papa on Controllers for more details.

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

Is it necessary to register a client script again after a post-back event?

Is it necessary to re-register a client-script block on all post-backs if it is added on the first page load like this? if (this.Page.IsPostBack==false) { if (this.Page.ClientScript .IsClientScriptI ...

What do you call a JavaScript function when it has a name

This code is confusing to me. It's not the usual JavaScript syntax for a function that I know of. Is this a specific function? Or perhaps it's a callback for when an update event occurs? Apologies for these beginner questions, as I am quite new t ...

Passing a MySQL connection to scripts in Express

After setting up the mysql connection with all the required parameters in app.js, is there a way to make it accessible to other scripts in routes/ without having to redeclare or require the mysql parameters again, simply by using client.query(..)? ...

Ways to expand CRA ESLint guidelines using the EXTEND_ESLINT environmental variable

Facebook's Create React App (CRA) recently introduced a new feature allowing users to customize the base ESLint rules. Recognizing that some cases may require further customization, it is now possible to extend the base ESLint config by setting the ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

What strategies can be implemented to minimize the use of if-else statements?

Is there a more efficient way to simplify this if-else statement? This code dynamically changes the picture based on integers retrieved from the database. I am looking for ways to optimize this code. if (val["soil_h"] < 21){ $("#ground").att ...

Step-by-step guide on activating a controller function following an Animation in Angular JS

I have hit a roadblock trying to connect a series of animations with a controller action. My goal is to: 1. click on a button/div, 2. Trigger an animation, 3. Once the animation finishes, execute a function in the controller to reset the button/div. I&a ...

Pressing the reset button on the search box triggers a JQuery and HTML function

I am new to this, so bear with me. I've simplified my styling for easy pasting here, but the concepts still apply. I have a list of items, a working search field, and functioning filter buttons. What I want is for the filter buttons to reset to &apos ...

ReactJS component experiencing issues with loading images

In my React project, there is a directory containing several images, and I am attempting to import them all into a carousel using Bootstrap. The current code looks like this: import Carousel from 'react-bootstrap/Carousel'; const slideImagesFold ...

Chrome showing random 0 status for $http and $ajax requests

Occasionally, an issue arises on the website where the browser starts returning status 0 for XMLHTTPRequest requests randomly. This problem applies to requests made through both the jquery ajax function and the $http resource in angularJS. Curiously, the ...

Exploring how RequireJS and AngularJS services communicate with the controller

RequireJS and AngularJS. I am encountering an error when trying to access the controller inside a service. The error message I receive is: 'Argument 'onCloseAlert' is not a function, got undefined.' This service is being called by an ...

Enabling the execution of returned scripts using JQuery AJAX

I have a hyperlink that I need to send a DELETE request using JQuery through AJAX. if(confirm("Do you wish to proceed?")) { $.ajax({ url: $(this).attr("href"), type: 'DELETE', success: function(result) { // Perform act ...

Sort function now accepts a limitless amount of arguments for sorting

We are tasked with creating a function that can take an unlimited number of arguments to sort an array by. For example: var data = [['John','London',35], ['Ricky','Kuala Lumpur',38], [' ...

I attempted to increase the value in an array by using the push() method, but I am uncertain about the proper way to do

I have this code that I'm using to organize the staff members in company1, but it seems to be creating a new list of arrays. Can someone assist me with this issue? Once I add the name and ID of the staff, the array will appear as follows: [{compan ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

Use the inline IF statement to adjust the icon class depending on the Flask variable

Is it feasible to achieve this using the inline if function? Alternatively, I could use JavaScript. While I've come across some similar posts here, the solutions provided were not exactly what I expected or were implemented in PHP. <i class="f ...

The registration feature powered by JQuery is experiencing technical difficulties and not functioning

Having trouble with a registration system on my website at *. When someone registers, it should either show an error message or display "true" if the registration is successful. I have a javascript file (http://pastebin.com/mv9CWZcT) set up to redirect the ...

How can you handle undefined values in the query object parameter when using Mongoose's Find function?

Alright: Sound.find({ what: req.query.what, where: req.query.where, date: req.query.date, hour: req.query.hour}, function(err, varToStoreResult, count) { //perform some actions }); Let's consider a scenario where only req.query.what has a ...

What is the correct procedure for utilizing variables in the parseJson function when working with string objects?

While working with the parseJson function, I have encountered a challenge where I need to incorporate a variable within three objects. Is there a way to merge a variable with the value of one object? Alternatively, can I utilize a third object to store t ...