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

The AngularJS routing template fails to load

I am currently working on the app.js file: 'use strict'; var app = angular.module('app', [ 'auth0', 'angular-storage', 'angular-jwt', 'ui.router', 'Environment', ...

What is Angular's approach to handling a dynamic and unprocessed JSON object?

When a JSON file is placed under assets, accessing it using something like http://localhost:4200/myapp.com/assets/hello.json will fetch the JSON file directly without any graphical user interface. This indicates that Angular must be able to return a raw JS ...

Building React applications with server-side rendering using custom HTML structures

I recently started using Suspense in my React app and decided to implement SSR. However, as I was going through the documentation at https://reactjs.org/docs/react-dom-server.html#rendertopipeablestream, I couldn't find a clear explanation on how to u ...

The combination of Array.pop and Array.indexOf is not functioning as expected

I'm having an issue with using Array.pop(Array.indexOf(value)). It seems to always delete the last element in the index, even if the value of that index is not what I intended. Can someone provide some guidance on how to resolve this? CheckBoxHandle ...

Testing the ui-router with an incorrect route for unit testing

After finding a helpful post on Stack Overflow about adding unit tests for ui-router, I decided to implement the following test: describe 'State: myApp', -> # Loading the module of the filter beforeEach module 'myApp' $rootS ...

There is an issue with transmitting data from an HTML page to the server and then retrieving data from the server

Upon running this code, I encountered an issue with sending and receiving data. I kindly request assistance in correcting my code. Highlighted below is the server-side code var http = require("http") ; var fs = require("fs") ; http.createServer(function( ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

Transforming Form Input into Request Payload for an AJAX Call

I'm facing a challenge in submitting my form data through a POST AJAX request and haven't been able to come across any solutions so far. Due to the dynamic creation of the form based on database content, I can't simply fetch the values usin ...

Exploring the contrast between 'completed' and 'upcoming' in callback functions within node.js

Within the passport documentation for authentication configuration, there is a function that appears rather intimidating as it utilizes the enigmatic function "done." passport.use(new LocalStrategy( function(username, password, done) { User.findOne( ...

Clicking an element to uncover more information

Currently, I am working on solving the second question within this series of problems. The task involves creating a functionality where clicking on a legislator's name displays additional information about them. You can view my progress so far by visi ...

Leveraging "setState" in React Native with Promises

I am facing a challenge in updating the state of a React Component with data obtained from an API call. I encountered an issue where using the setState function within the promise resulted in an error "Type Error: _this2.setState is not a function" in Reac ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

Utilize jQuery to swiftly align elements within a designated container

Check out my JSFiddle example: http://jsfiddle.net/c62rsff3/ I'm attempting to implement snapping behavior between 2 elements using this code: $('.draggable-elements').draggable({ snap: true }); In addition, I've defined a container ...

Looking to create a loop that continues as long as a JSON dataset remains assigned to a specific variable

I've been trying to retrieve JSON data, but I seem to have hit a snag. I'm not sure where I went wrong or how to correct it. [ { "userId": 1, "title": "A", "body": "B" }, { "userId": 1, "title": "C", "body": "D" }, { "userId": 2, "title": "E", " ...

There was a TypeError encountered in a Node application, stating: "Unable to access the 'trim' property of an undefined

Currently, I am developing a JavaScript application that follows the MVC model. In the controllers, there is a userController.js file, and in the models, there is a user.js file which contains a cleanup function. However, I am encountering a TypeError: Can ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Preventing a webpage's CSS from affecting an iframe loading an HTML document

Whenever I load an iframe, it seems to change a bit. Do I need to apply some kind of reset or adjustment? How can I ensure that the content within the iframe looks consistent no matter what page it's loaded into? ...

Visual Studio Terminal displaying "Module Not Found" error message

After successfully downloading nodejs onto my computer, I created a javascript file and stored it in a folder on my desktop. However, when I tried to run the JS code using the Visual Studio terminal, I encountered the following error message. I am confiden ...