Can you clarify the meaning of 'this' in an AngularJS controller?

index.html

 <body ng-controller="StoreController as s">
  <h1 ng-click="s.changeValFunc()">{{s.carname}}</h1>
  <h2>{{s.carname}}</h2>
  </body>

app.js

var app = angular.module('store', []);
app.controller('StoreController', function() {
    this.carname = "Volvo";
    this.changeValFunc = function(){
        this.carname="BMW";
    }
});

When the h1 tag is clicked, both h1 and h2 display BMW instead of Volvo. The confusion lies in how controller properties are shared across views when clicking on elements. It seems like the "this" keyword refers to the current element being interacted with, causing a change for all elements referencing the same property.

Answer №1

When you use the new keyword to instantiate a controller function, it creates an instance that functions like this:

function ShoppingCartController() {
    this.item = "Shoes";
    this.updateItemFunc = function () {
        this.item = "Pants";
    }
};

var cart = new ShoppingCartController();

console.log(cart.item); // Shoes

The variable cart in your code references the newly created instance of the ShoppingCartController function, which contains the specified attributes set within the constructor function. For more insights on how the this keyword operates, refer to Understanding the concept of 'this'.

Answer №2

When referring to your specific scenario, the focus is on the controller itself.

Any attribute within that controller can be easily accessed by using this code:

this.attribute

In this instance, you are "assigning" the controller to a parent element like so:

<body ng-controller="StoreController as s">

This action essentially creates an instance of the StoreController for the body element.

By modifying the carname attribute, you are affecting the entire controller.

If you have a basic understanding of object-oriented programming, you can view the controller as a Class and use 'this' to reference the instance of that class.

In JavaScript, 'this' can exhibit some peculiar behavior at times, as mentioned by deceze. It may be beneficial to explore posts that delve into how 'this' operates in JS.

I trust this explanation proves helpful.

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

Get the characters from a JavaScript string, but make sure to exclude

There is a text string that I need to work with: TEST:ABCDEGF:18:32 This text includes letters and numbers, but I want to extract all of them excluding the : character. Previously, I was using the following code successfully: lines.split(":"); However ...

Sending data that was retrieved asynchronously to a directive

Currently, I am working with an AngularJS controller that retrieves JSON data asynchronously using a $http.get() method and then assigns this data to a scope variable. An overview of the controller code: mapsControllers.controller('interactionsContr ...

Converting DateTime objects into JSON format for use in AJAX calls

When utilizing my AJAX method, it returns a view model that is serialized as a data structure using JavaScriptSerializer().Serialize(). Among this data are several nullable DateTime? properties. I recently discovered that these dates appear in JavaScript ...

Using Node.js with Express to seamlessly pass objects to EJS templates

I have a scenario where I am passing an object to my template and I want to display the details of that object in HTML. app.get('/', function (req, res) { var user = req.session.passport.user; if ( user != 'undefined' ){ ...

Executing Protractor tests within the Maven build workflow

Looking for a way to integrate protractor tests into my Maven project's build process. I want the tests to run after compilation and for the build to only pass if the tests are successful. Currently using the 'com.github.eirslett' Maven plug ...

Enhanced Slider Display featuring Multiple Posts for Improved Performance

My Sample Page features a slider that displays over 200 posts, each containing 5 images. However, the slider loads all the images at once, causing my page speed to be very slow. I am looking for an optimized way to display the slider without compromising l ...

What is the best way to incorporate data from a foreach method into a function call within an HTML string?

Having trouble calling a function with data from a foreach loop while generating HTML cards and buttons from an array. The issue seems to be in the renderProducts() method. /// <reference path="coin.ts" /> /// <reference path="prod ...

How can I send various maximum values to the Backbone template?

Although in theory, it may seem simple, I am unsure about the exact code to use. In a view, if I define a variable max that retrieves an attribute called points from a collection, I can pass this variable as an object into my template using maxPoints.toJS ...

The flow union type operates smoothly without any errors occurring

In the code snippet below, I have defined a type 'Something' which can have three possible values: 'A', 'B', or 'C'. The function 'f' takes an object of type Something as input and returns a string based on ...

Steps for populating an ng-table with data retrieved from a REST web service that returns a JSON format

I am currently facing an issue while trying to load my table from a JSON response that I receive from REST web services in SpringMVC. The error message I received indicates that my REST method does not support the GET request. The URL mapped in my control ...

Organizing data in a database the arrangement way

I'm looking to populate an array with values for "name" and "nickname" extracted from an SQLITE database and then display them in an alert box. This task is part of a JavaScript project developed using Titanium Appcelerator. Below is the code snippe ...

Utilizing Angular to augment existing items in local storage

Hey everyone, I'm facing an issue with localStorage that I can't seem to figure out. I have a form where the first step collects name and gender, and the second step asks for weight and height. The data from step 1 is saved in localStorage, but ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Issue: Attempting to send a POST request to the specified API endpoint for creating a product category resulted in a 500 Internal Server Error

My current task involves inserting data into a table using the POST method with an Angular service function. angular.module("productCategoryModule") .factory("productCategoryService",productCategoryService); productCategoryService.$inject = ['$http& ...

Attempting to establish a connection with a MySQL database through the utilization of Node.js in combination with the mysql javascript client

Recently, I've been facing a challenge connecting to a MySQL database from my electron app: <script> var mysql = require('mysql'); var connection = mysql.createConnection({ host : '*********', ...

What is the best way to extract JSON data from a remote URL?

Having recently started with JavaScript, I am looking to parse JSON from an external URL using pure JavaScript. Currently, I have the following code: var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, tr ...

AngularJS: Incorporate a loading spinner at the beginning of the document object model

After spending some time searching for the best way to accomplish this task without any luck, I am starting to doubt my search skills or perhaps no one has posed this question before. Despite leaning towards the former, I still find myself at a dead end. ...

Navigating through the DOM using JavaScript or regular expressions

I have a DOM string called innerHTML and I am looking to extract or display the node value using either JavaScript's DOM API or JavaScript RegEx. "<nobr> <label class="datatable-header-sortable-child" onmousedown="javascript:giveFeedback(&ap ...

What is the best way to pass a div element and a variable from a Child component back to a Parent component in Next.js/React?

My goal is to create a webapp that, when an item in the list generated by the child component is clicked, displays the corresponding image in a div within the parent component. After some trial and error, I managed to generate the list in the child compone ...

"Revolutionary AJAX-enabled PHP social commenting system with multi-form support

Why is it that when I submit forms using these ajax functions in PHP, they only send to the first form on the page? I have multiple forms under each article and I want them to be submitted separately. What am I doing wrong? ...