Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this:

myApp.controller('MyController', ['$scope', function($scope) {
        var vm = $scope.vm = {name:'savo'};
    }
]);

Initially, this multiple assignment seemed simple enough to understand. However, things got more complex when I tried coding something like this:

myApp.controller('MyController', ['$scope', function($scope) {
       var vm = $scope.vm = {name:'savo'};
       vm.age = 18;
    }
]);

Accompanied by HTML similar to the following:

<div ng-controller="MyController">
    <pre>{{vm}}</pre>
    <pre>{{vm.name}}</pre>
    <pre>{{vm.age}}</pre>
</div>

Upon viewing the results in my browser, I noticed that the vm object in the $scope also reflected the added attribute age.

This brought up a question for me: Why does adding an attribute to vm within the controller affect the vm object in the $scope as well?

In regular JavaScript, this behavior wouldn't be expected. Renaming either of the vm variables doesn't alter anything.

As someone new to angularJS, this aspect is quite perplexing for me. Any insights or assistance would be greatly appreciated!

Lastly, I'm curious about the choice of naming conventions in angularJS, particularly the use of vm. Could it possibly stand for an abbreviation of some sort?

Answer №1

I'm curious about something: Why does the controller give the vm a attribute age, and then it also appears in the $scope?

The reason for this is that both variables vm and $scope.vm point to the same object. So when you modify one by adding a new property, the other one gets updated as well.

It doesn't work this way with native JavaScript.

It seems like you might be mistaken here. This behavior is common because non-primitive types (like objects, functions, arrays) in JavaScript are passed by reference.

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

Storing JWT API tokens in a secure location

Currently, I am in the process of developing the API portion for an application and focusing on implementing JWT authentication. At this point, I am generating a token and sending it back to the front-end as part of a JSON object when a user is created. Ho ...

The term "GAPI" has not been declared or defined within the Svelte

Encountering an issue while trying to incorporate the Youtube data API into my Svelte application. Upon loading the site, the error message displayed is: Uncaught ReferenceError: gapi is not defined Reviewing the relevant code reveals: <svelte:head> ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

"Encountered an error while trying to define a Boolean variable due

I am in the process of creating a TF2 trading bot with price checking capabilities. I encounter an issue while trying to define a boolean variable to determine if the item is priced in keys or not. My attempt at replacing isKeys with data[baseName].prices ...

Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded. For instance, I have an example of an isRegister ...

Issue with JavaScript Date.parse function not functioning as expected

I have implemented a date validation method in my application to check if a given date is valid or not. myApp.isValidDate = function(date) { var timestamp; timestamp = Date.parse(date); if (isNaN(timestamp) === false) { return true; } return ...

Is it possible to showcase a dropdown list within a constantly changing table?

I have a table code snippet that I need help with <fieldset class="tabular"><legend><%= l(:redmine_taskjuggler) %></legend> <%= labelled_fields_for(@issue) do |f| %> <div id="taskjuggler" class="attributes"> <div cl ...

What is the process for printing with JQuery?

I have nested divs with dynamically generated images in my HTML code. My problem is that when I click the print button, I want the corresponding image to be printed. <div id="outputTemp" style="display:none"> <div id="rightoutputimgae"> <di ...

Elevate Angular version 1.4 to the latest update

My current project structure is displayed in the image linked below. I am currently working on upgrading the project to a higher version. https://i.stack.imgur.com/noavm.png I would greatly appreciate any suggestions or advice on how to utilize ngUpgrade ...

Retrieve the designated element from an array of JSON data in SPLUNK

As a newcomer to the world of Splunk, I am facing a challenge with handling JSON data. Here is an example of the JSON data I am working with: "request": { "headers": [ { "name": "x-real-ip", "value": "10.31.68.186" ...

Issues with the event firing in the Polymer component for google-signin?

I recently set up a new starter-kit project using polymer-cli 1.7 and I'm attempting to incorporate Google authentication utilizing the google-signin element. Although the sign in button appears and works for signing in, the signedIn property isn&apo ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

AngularJS modal not functioning properly after sending $http request

I have successfully implemented a pop-up modal in my Angular page using code from a reliable source. However, when I include a button for an HTTP request on the same page, the functionality of the AngularJS modal stops working after the HTTP request is mad ...

Setting up package.json to relocate node_modules to a different directory outside of the web application:

My web app is currently located in C:\Google-drive\vue-app. When I run the command yarn build, it installs a node_modules folder within C:\Google-drive\vue-app. However, since I am using Google Drive to sync my web app source code to Go ...

When debugging in ASP MVC4, JavaScript will only evaluate HiddenFor once you've paused to inspect it

Struggling with evaluating a hidden field in JavaScript (ASP MVC4). I've set up a model in my View with a hidden input for one of the properties. @Html.HiddenFor(mdl => mdl.FilterByUser, new { @id = "filterByUserId" }) Within my Helper, I have a ...

Passing data between API tests in JavaScript

I'm encountering an issue where I need to create e2e api tests. The goal of the first test is to obtain a token for an unauthorized user, use that token in the method header for the second test to return a token for an authorized user, and then contin ...

What is a more effective method for linking values with variables in an object?

Can you suggest a more efficient way to write this in JavaScript? let foo; if(bar) { foo = bar.value; } I am attempting to prevent a react error from occurring when `bar` is null if I were to use const foo = bar.value. ...

What sets Redux React-Native apart: Exploring the nuances between utilizing useSelector in react-redux versus connect

I believe they were identical because both extracted the content from the store. What could potentially differentiate them? ...

encountering a problem with permissions while attempting to update npm

Has anyone encountered a permission error with npm when trying to update to the latest version? I recently tried updating npm and received this error message. I'm unsure of how to resolve it. Any suggestions? marshalls-MacBook-Air:Desktop marshall$ n ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...