Comparing "this" and $scope within the context of Angular

I have gone through similar questions and their answers, but I am still struggling to understand this. Any assistance on this would be greatly appreciated.

The code snippet below functions correctly. However, if I substitute $scope with this before the bindTest and clickTest functions (lines 3 and 6), it fails to work. Can someone explain why this is happening? Based on my understanding, using $scope should work in this scenario.

Conversely, replacing $scope with this before offOrOn (line 8) results in it not working.

angular.module('myTestApp', [])
        .controller('MyTestController', function($scope) {
          this.bindTest = function() {
            console.log("bindTest");
          }; 
          this.clickTest = function() {
            console.log("clickTest");
            $scope.offOrOn = 'on';
          };       
        });
button {
 height:25px;
 width:25px; 
}
.on {
 background-color:red;
}
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myTestApp" ng-controller="MyTestController as tester">
 <p ng-bind="tester.bindTest()"></p>
 <button ng-class="offOrOn" ng-click="tester.clickTest()"></button>
</div>
</body>

Additionally, I attempted to create a fiddle, but encountered issues where it wouldn't load the module according to the Chrome dev console. I'm curious about what could be causing this problem. Nevertheless, it's beneficial that stackoverflow now offers a similar functioning alternative!

Answer №1

The utilization of the controller as syntax enables accessibility to anything added to this through tester., while items added to $scope can only be used without prefixed by test..

It becomes evident why this.offOrOn is ineffective: The absence of tester.offOrOn in your HTML.

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

Unable to select an option in AngularJs using ng-repeat

How can I preselect an option in a select element rendered by ng-repeat? <body ng-app ng-controller="AppCtrl"> <div>Chosen leverage: {{openAccount.leverage}}</div> <select class="form-control" name="leverage" ng-model="openAcc ...

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

Discovering how to choose an element from a list fetched through ajax in Angular

It's quite strange to me. Angular allows for selecting by reference, but not by value. Let me explain my situation: I have a form that lets users edit a model. I use ajax to fetch both the model and a list of possible values for one of the model&apo ...

Utilizing modal functionality in CakePHP 3 (or: Incorporating JavaScript within Controllers)

I have a typical form that was created using cake/bake. After the form is submitted, my controller checks a simple condition: If condition A is met, it will just save the data using patchEntity($foo, $this->request->getData()) If condition B is me ...

Learn how to implement Basic Authentication in your Express application using the express-basic-auth package. You can easily trigger login and logout

When it comes to logging out a user who has logged in using basic Auth, I am exploring different options by consulting various sources like: link1 link2 In my application, I have implemented express-basic-auth to secure certain routes. Here is an example ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

Is the row removed from the table after successful deletion?

I am struggling to remove the deleted row from the table. The code I tried is not working as expected. Here is the scenario: When a user clicks on the delete link/button, it sends a delete request and removes the data from the Database. After successful de ...

Trouble with importing css in Angular webpack due to ui-bootstrap integration

Currently, I am developing an Angular application with Webpack and was looking to incorporate Bootstrap for styling purposes. To achieve this, I first installed 'ui-bootstrap' using npm install angular-ui-bootstrap --save-dev. After installation ...

Conceal a script-generated div using CSS styling

Using the code below, you can create an HTML chatbox with a link in the top panel and multiple child divs. The structure is as follows: cgroup is the parent of CBG, which is the parent of CGW, and CGW is the parent of the div I want to hide. How can I u ...

Incorrect embeds are dispatched when removing messages per user and term

Recently, I've been delving into the world of JavaScript to develop a custom Purge Command. I took inspiration from a Purge Command written in TypeScript by reconlx for their DJS v13 command handler, and with some tweaks, I managed to make it compatib ...

Personalized Pagination for Data Tables

I have a client who needs a customized pagination view for DataTable. I want the pagination to look exactly like the image provided. https://i.sstatic.net/FFzkM.png To achieve this, I made modifications to the datables.js code. DataTable.js: $.extend(e ...

Leveraging the power of HTML 5 to dynamically insert content into a jQuery table

I am experiencing an issue with my jquery stock ticker. It displays the latest stocks including Company Name, stock price, and percentage changed. The stock price can be in GBP, USD, or YEN, but the current ticker does not indicate the currency. I attemp ...

Dynamically loading various compositions of EDGE

I'm currently working on developing a testing system for edge-animate compositions. The goal is to be able to load different compositions and verify that they are displaying correctly, as well as make changes to their customizable fields. I attempted ...

Tips for resolving asynchronous s3 resolver uploads using Node.js and GraphQL

My goal is to upload an image and then save the link to a user in the database. Below is my GraphQL resolver implementation: resolve: async (_root, args, { user, prisma }) => { .... const params = { Bucket: s3BucketName, ...

What could be causing the slow compilation of my Next.js pages within the app directory, and what steps can be taken to improve the speed of this

Currently, I am working on a Next.js project that uses the 'app' directory structure. However, during local development, I have been facing significant delays in compile times. Here's a breakdown of the compile times I am encountering: - Th ...

How can I create a consistent copy button function for an HTML table that works the same across different browsers like Firefox and Chrome?

I am encountering an issue where copying the second row of an HTML table to paste it in an Excel file works perfectly in Firefox, but not in Chrome. When pasting in Chrome, the cells do not match and only the HTML inside the table cells is retained. I am u ...

Enhancing the functionality of angular-messages is impacting the overall design of

Displaying here is the current state of my login form: https://i.sstatic.net/EMcjF.png However, subsequent to upgrading angular-message to version 1.4 and higher, the layout transforms into this: https://i.sstatic.net/vVBHf.png Sharing my source code f ...

Encountered an error while running npm run dev on a Laravel Vue 3 project: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],

I am facing an issue in my Laravel 9 Vue 3 project. When I run php artisan serve and then npm run dev, I encounter the following error: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'di ...

The implementation of pipelining for server-side processing

Initially, this function is set up to work with $_GET. However, after incorporating feedback from this discussion, I made adjustments to the function which resulted in an error message being displayed by Firebug. The error message reads: "json.aaData is ...

Overlap of sub menus

Seeking assistance from a CSS expert for a challenge I am facing. I am currently working on a toggle menu for mobile view, and encountering issues with the submenu. Any list item placed below another one with children is not visible. Removing the parent l ...