Struggling to grasp the concept of nested scope within AngularJs

I found myself puzzled while reading an article on this particular website (pitfall #5):

My query is:

  1. Does this situation resemble having two variables with the same name in plain JavaScript, where one is locally defined (e.g. within a nested function) and one is globally defined (e.g. window.onload), causing the local one to always override the global one?

  2. I grasp that $scope.variable should point to a model containing values, but I'm unsure if it makes a difference if they share the same name regardless of using dot syntax. I'm unclear on how adding a "." dot would impact the OUTPUT VALUE mentioned above. For instance, replacing them with {{user.name}}. How does this recommended practice function?

The code snippet from the website aims to show that if the 2nd {{username}} changes, the 1st {{username}} remains unchanged.

HTML:

<span>Outside Controller: Your name is: {{username}}</span>
<div ng-controller="SignupController">
    <span>Inside Controller: Your name is: {{username}}</span>
    <fieldset legend="User details">
    <input ng-model="username" />
    </fieldset>
</div>

JS:

var app = angular.module('app', []);
app.controller('SignupController', function($scope){});

Answer №1

Similar to prototypal inheritance in JavaScript, this concept works.

function Jedi(){}
Jedi.prototype.name = 'Luke';

For example, when you execute this:

var obiwan = new Jedi();
console.log(obiwan.name); //Luke

However, if I were to do the following:

var obiwan = new Jedi();
obiwan.name = 'Obi-wan';
console.log(obiwan.name); //Obi-wan

var luke= new Jedi();
console.log(luke.name); //Luke

This illustrates how JavaScript handles properties. When a property is accessed, it searches for it within the object first, then in its prototype, and so on until it reaches the top of the prototype chain (if not found).

When assigning a value to a property that doesn't exist in the object already, it creates that field in the object itself. From that point onwards, the value retrieved when accessing the property is directly from the object, not its prototype.

An approach suggested in Angular is to store model data as objects rather than direct fields in the scope to avoid this behavior. For instance:

function Jedi()
Jedi.protype.data = {name: 'Luke'};

var obiwan = new Jedi();
obiwan.data.name = 'Obi-wan';

var luke= new Jedi();
console.log(luke.data.name); //Obi-wan

In this scenario, the prototypal inheritance revolves around the data field, which all objects share.

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

Can you please explain the distinction between the statements var a = b = 2 and var a = 2; var b = 2;

Whenever I try to declare a variable within a function, I encounter an issue. var b = 44; function test(){ var a = b = 2; } However, the following code works without any problems: var b = 44; function test(){ var a; var b = 2; } The global ...

Adjust the dimensions of a Three.js-generated 3D Cylinder in real-time

Is it possible to dynamically change the dimensions of a 3D cylinder created using Three.js, similar to how we can adjust the size of a cube in this live example: http://jsfiddle.net/EtSf3/4/ Below is the code I have for the cylinder: HTML: <script s ...

Incorporate payment processing functionality into your IONIC app by connecting a

Do not flag this question as a duplicate or already answered. If you have knowledge on this subject, please provide an answer. I am attempting to incorporate the payumoney payment gateway into my hybrid app. After following several tutorials, I have resor ...

Calculate how frequently an element showcases a particular style

I attempted to tally the occurrences of a specific class on an element, but I keep encountering the error message: $(...)[c].css is not a function Does jQuery have it out for me? Below is the code snippet in question: // hide headings of empty lists le ...

Using Jquery to attach an event to a particular div which is part of a group of divs sharing

I am trying to implement a mouseup event on a series of divs that, when clicked, will reveal a child div ('menu'). All the parent divs have the same class. Here is an example: <div class="container"> <div class="menu"><p>Text ...

sending the AJAX request from back to the original JavaScript function

Here presents an issue. I am dealing with an HTML Form that contains a submit button with an onclick=validationFunction(). When this button is clicked, the form values are passed to the mentioned function. Within this function, the form values undergo va ...

Identify modifications in the input and at the same time update another input

I currently have two input text boxes. My goal is to synchronize the content of the second input box whenever the first input box is changed. I attempted to achieve this using this code snippet. However, I encountered an issue where the synchronization on ...

Scripts for Azure mobile services

As a newcomer to server scripts, I am facing an issue that I believe has a simple solution, although I have been unable to find the answer so far. My current setup involves using azure mobile services for retrieving and inputting user information, with a f ...

Developing an AngularJS application using Maven within the Eclipse environment

We are currently working on a cutting-edge single-page application (SPA) where the front end is being built with AngularJS and the business logic is being handled by RESTful Web Services using JAX-RS. Our development environment consists of Eclipse as our ...

Issue: Debug Failure. Invalid expression: import= for internal module references should have been addressed in a previous transformer

While working on my Nest build script, I encountered the following error message: Error Debug Failure. False expression: import= for internal module references should be handled in an earlier transformer. I am having trouble comprehending what this erro ...

What could be the reason for my SQL query functioning correctly in my editor, but not in my JavaScript function?

When I run my SQL statement in my SQL editor, it works perfectly fine. However, when I try to use it in my JavaScript function, I get an error saying there is an invalid column for my client ID. function getFeedposts(data) { var limit = data.dollarLimit; ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

The second instance of a React Paginate on the same page remains static and does not trigger a

Having a bit of trouble with using react-paginate for pagination - I have two instances on the same page (one at the top and one at the bottom). When a new prop is received, only the top instance gets re-rendered. The code seems to be working fine as all ...

How can the required flag be integrated with rules validation in react-hook-form and material-ui (mui) for inputs?

Currently, I have implemented react-hook-forms for handling form functionality and validation in our application. On the other hand, we are utilizing MUI/Material-UI as our component library. One issue that arises is that MUI automatically adds a * to inpu ...

Is it possible to impose a different style on an element from another culture?

I am currently developing a themes library along with a demo page. The challenge I'm facing is that the demo page needs to showcase styles from the library without using all of the elements. For instance, consider the following style in an external s ...

Does ng-include fetch the included HTML files individually or merge them into a single HTML file before serving?

Is there a performance impact when using the ng-include Angular directive, in terms of having included HTML files downloaded as separate entities to the user's browsers? I am utilizing a CDN like AWS CloudFront instead of a node server to serve the H ...

Utilizing Bootstrap's Multi-Grid System

I am currently working on implementing a Bootstrap grid design that resembles pic1.jpg. However, I am facing challenges in achieving the desired layout, as pic2.jpg shows the current scenario. Below, I have shared the code I am using. pic1.jpg :- ! pic2. ...

Understanding the extent of testing coverage in a project using karma and webpack

For my project, I am incorporating ES6 syntax and testing my code with Karma. While I have successfully set up testing, I encountered an issue with the coverage report. Instead of including the source code, the coverage report is highlighting spec file ...

Page refresh enhances hover effect style

Is there a way to maintain a "hover" style even after a page refresh if the user does not move their mouse? The hover effect is only activated on mouse enter/mouseover events, so when the page refreshes, the style doesn't persist unless the user inter ...

Disregard all numbers following the period in regex

I have developed a function to format numbers by adding commas every 3 digits: formatNumber: (num) => { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') }, The issue with this function is that it also add ...