Utilizing Angular's Scope Functionality

I am a novice in the world of AngularJS.

Currently, I am delving into the expert's codebase and looking to customize the directives for educational purposes.

Interestingly, the expert consistently includes:

this.scope = $scope;

at the start of each controller. I'm curious about the purpose of this statement since only $scope is used throughout the code afterwards.

Answer №1

this reference was pointing towards $scope rather than the controller itself.

this

  • When the constructor function of the controller is invoked, this refers to the controller.
  • When a function defined within a $scope object is called, this represents the "scope in effect at the time when
    the function was executed". It may or may not be the same as the $scope the function is defined on. **Therefore, inside the function, this and $scope can differ.

$scope

  • Each controller has an assigned $scope object.
  • A controller (constructor) function is tasked with defining model properties and functions/behavior on its corresponding $scope.
  • Only methods declared on this $scope object (and potentially on parent scope objects through prototypical inheritance) are accessible from the HTML/view. For instance, via ng-click, filters, etc.

courtesy of Mark Rajcok extracted from How does 'this' and $scope work in AngularJS controllers

without using this

app.controller('MyCtrl', function($scope){
  $scope.doStuff = function(){
    //A very lengthy function body
  };
});

with using this

var MyCtrl = function($scope){
  var _this = this;

  $scope.doStuff = function(){
    _this.doStuff();
  };
};

MyCtrl.prototype.doStuff = function(){
  //A very lengthy function body
};

MyCtrl.$inject = ['$scope'];

app.controller('MyCtrl', MyCtrl);

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

The execution of my code differs between running it locally and in online code editors like CodePen or Plunker

Using jQuery Terminal, I have the following code: function display() { for (var i = 0; i < 100; ++i) { this.echo('line ' + i, { flush: false }); } this.flush(); setTimeout(function() { //thi ...

Encountering a "window not defined" error while implementing Leaflet in my Nuxt JS application

I'm encountering an issue while trying to generate my nuxt app, specifically on my 'Area' page. It seems like the error is related to the leaflet maps being used on this page. https://i.sstatic.net/Cj9ai.png Initially, I attempted to resol ...

Creating an HTML layout or template directly within a JavaScript bookmarklet

Currently, I am using a bookmarklet that generates a user interface for interaction. The method I have been using involves creating elements using $('<element>').addClass().css({..});, but this approach is proving to be difficult to maintai ...

Limit the selection of 'pickable' attributes following selections in the picking function (TypeScript)

In the codebase I'm working on, I recently added a useful util function: const pick = <T extends object, P extends keyof T, R = Pick<T,P>>( obj: T, keys: P[] ): R => { if (!obj) return {} as R return keys.reduce((acc, key) => { re ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

What is preventing JSON.parse() from extracting the data from this json string in this particular scenario?

One of the challenges I'm currently facing involves extracting a specific item from a JSON-formatted string and displaying it on the screen using .innerHTML. The JSON string, named myData, is retrieved from a MySQL database via PHP. To achieve this, ...

Create a duplicate array with all distinct elements - JavaScript

Help needed: I am facing an issue with an array of objects. My goal is to create a unique copy of this array to prevent any changes in the original one when modifications are made to the new array. I have experimented with several methods, including: let ...

Issue encountered: React module not detected while attempting to execute npm start command

While developing my react app, I encountered an issue when trying to run 'npm start'. The application was working as expected until I faced a bug that prompted me to update my node version for a potential fix. After upgrading to node v16.13.2 and ...

Determine the maximum array size in Javascript

Having trouble setting a limit in my custom lightbox for a gallery <script> var imagenumber = 0; function btnleft(){ load = imagenumber-=1; document.getElementById('lightboxcontent').innerHTML=imagelist[load]; ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...

Unveiling the Secrets of Encoding and Decoding JSON within a Concealed HTML

I am in the process of creating a unique control using HTML and JQuery that will showcase a specific text value. Users will have the ability to input various key/value pairs. Here is the current code snippet I am working with: <input id="keyValue" type ...

Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage : var percentage = Math.round(sum * 100 / total); Next, I place this value here : <di ...

Cloned bootstrap nav tabs are controlled just like the original version

I have a unique scenario where I need to generate a series of "cards" with tabs on top (each card having tabs). To accomplish this, my plan was to use a template element that I can clone and then populate. Everything seems to work fine, except for the tabs ...

Tips for accessing and adjusting an ngModel that is populated by an attribute assigned via ngFor

Looking for guidance on how to modify an input with ngModel attribute derived from ngFor, and update its value in the component. Here is my code snippet for reference: HTML FRONT The goal here is to adjust [(ngModel)] = "item.days" based on button click ...

What is the best way to develop a unique animation for every v-card?

Is there a way to customize each animation so that it is specific to the selected v-card? Right now, when one card is clicked, all of them play the same animation. data: () => ({ show: true, images: [ {url:require('@/assets/london. ...

Having trouble retrieving the value of a constant within an AngularJS service

Within my module, I have included a constant as shown below: var app = angular.module("myapp", ["ngRoute"]).constant("myConfig", { "url": "http://localhost", "port": "80" }); I attempted to retrieve the value of the constant in my service like this but I ...

The variable req.body.Dates has not been declared

I am currently working on a project that involves dynamically populating two drop down menus using SQL Server. Depending on the selected items, I need to load a specific ejs template using AJAX. My goal is to load data based on the selected criteria. For e ...

Troubleshooting Problems with Deploying Next Js on Firebase

I am currently working on a new Next Js application and have successfully deployed it on Vercel by linking the GitLab project. Now, I need to deploy the same project on Firebase. Here's what I have tried so far: - Ran firebase init This command gen ...

Having issues with an AngularJS test in Protractor where the Jasmine spec seems to be timing out on the 'expect' clause. Could resetting the WebDriver Control Flow help?

Currently in the process of creating a series of tests using Protractor to validate an AngularJS application that my company is working on. While running through the tests, I encountered a failure with one of them and couldn't determine the root cause ...