The Angular feature allows for pass-by-reference of scope variables in functions

Query

Can a scope variable (specifically an array) be passed by reference to a function triggered by ng-click, and can the value of that variable be manipulated?

Update: To clarify further, my objective is to avoid accessing $scope in $scope.app.onItemClick.

Illustration

Javascript:

(function() {
    angular.module('test', [])
    
    angular.module('test').controller('test',['$scope', function ($scope) {
      $scope.app = {};
      
      $scope.app.primarySet = [
        'test1',
        'test2',
        'test3'
      ]
      
      $scope.app.workingSet = [
        'test4',
        'test5',
        'test6'
      ]
      
      /*
       * Tries to assign $scope.app.primarySet to $scope.app.workingSet using references to those values.
       */
      $scope.app.onItemClick = function (primarySet, workingSet) {
        primarySet = workingSet
      }
    }])
  })()

Relevant HTML:

<button type="button" ng-click="app.onItemClick(app.primarySet, app.workingSet)">Update Primary Set</button>

Please refer to this Plunker for more context on this code.

In this code snippet, I expected $scope.app.primarySet to be set equal to $scope.app.workingSet when the button is clicked. However, this does not happen. Although within the function's scope, primarySet is assigned to workingSet, $scope.app.primarySet remains unchanged.

Reasoning

I am driven by insights from this response on Stack Overflow. I agree that it would be simpler to test methods that modify scope if direct referencing is avoided. This approach also seems clearer than having a function directly alter the scope.

Prior Investigations

The only source I found related to this topic is this question on Stack Overflow. While similar, the issue here concerns manipulating a string parameter, which supposedly cannot be changed as anticipated with a reference.

Answer №1

To modify the primarySet within $scope, you need to pass the $scope.app through onItemClick like this:


(function() {
  angular.module('example', [])

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

    $scope.app.primarySet = [
      'item1',
      'item2',
      'item3'
    ]

    $scope.app.secondarySet = [
      'item4',
      'item5',
      'item6'
    ]

    /*
     * Updates $scope.app.primarySet with reference to $scope.app.workingSet.
     */
    $scope.app.onItemClick = function (app, secondarySet) {
      app.primarySet = secondarySet;
    }
  }])
})()

<button type="button" ng-click="app.onItemClick(app, app.secondarySet)">Modify Primary Set</button>

It's important to pass the entire object in order to avoid passing just the value of an array.

Answer №2

In JavaScript, it is possible to access object properties as keys. An example of how you can update a template using this feature is shown below:

<button type="button" ng-click="app.onItemClick(app, 'primarySet', app, 'workingSet')">Update Primary Set</button>

To make the necessary changes, update the onItemClick method like so:

  $scope.app.onItemClick = function ( leftObject, leftProperty, rightObject, rightProperty) {
    leftObject[leftProperty] = rightObject[rightProperty];
  }

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

How can you ensure a cohesive visual style throughout various Razor and HTML views?

In my ASP.Net MVC 5 application, I have a Layout.cshtml and HTML view page included. However, I want to maintain a consistent look and feel across multiple views in the application. I am aware that this can be achieved by using a Razor view page with the f ...

How to adjust cell alignment in Handsontable

Handsontable showcases cell alignment options in the align cell demo: Horizontal Left Center Right Justify Vertical Top Middle Bottom Displayed below is a screenshot: To retrieve data, utilize the following code snippet: $('#table-wrapper&ap ...

Mapping JSON to Java objects in Spring MVC causes a 400 error (Bad Request)

Whenever I try to submit the form, I encounter a 400 (Bad Request) error. My setup includes Jackson API jackson-core-asl-1.9.10.jar and jackson-mapper-asl-1.9.10.jar. Although I am able to receive JSON data, I am facing issues while submitting it. myjava ...

Store the output of JavaScript in a PHP variable

My objective is to convert any image to base 64 and then store the converted string in a PHP variable before inserting it into my database. JavaScript Code: function uploadFile() { if (this.files && this.files[0]) { var FR= new FileReader ...

Launch in a new window using JavaScript

Check out my interactive map here. Currently, when I click on different sections of the map, the target page opens in the same window. However, I would like it to open in a new window instead. <iframe src="http://bluewingholidays.com/map/map.html ...

Downloading multiple files on both iOS and Android devices

Is there a way to download assets (mp3/jpeg) in an Asynchronous manner? I have over 200 files in each case and the process is taking too long. Are there any techniques to speed up the download process on both iOS and Android? ...

Ways to create a class method to increase a counter?

Can someone help me figure out how to create a custom function or class from the code below? I want to be able to import this module in order to easily increment a count whenever an event occurs in my application. I'm tired of having to manually inpu ...

I require assistance in troubleshooting and repairing my HTML and JavaScript code

I am working on creating a feature where users can input their upcoming birthday date and receive an alert showing how many days are left until then. However, I encountered an issue where the alert displays NaN (Not a Number) before the birthday is entered ...

Incorporate Y-axis titles onto D3 bar chart using the attribute 'name' from JSON data

While following the tutorial on creating a bar chart, I encountered an issue in step three. The bars are rotated to columns, but I am struggling to iterate over a JSON dataset and add Y-axis labels for each bar using the name attribute from the returned JS ...

Unexpected dependency mysteriously appeared in package.json during npm install

I'm in the process of developing a project using npm 7.24.0 and executing npm install --lockfile-version 2 --legacy-peer-deps After the project is built, it adds an additional line to package.json "dependencies": { "2": &quo ...

Using React Native to implement a slide bar that displays an image

Currently working on an app and aiming to implement a slider feature for emoji selection. Despite searching for suitable packages, I have not been able to find one that fits my requirements. As a result, I decided to use the react native slider instead. Ho ...

Discovering the technique for accessing the parent component in AngularJS 1.5

Hey there, I'm currently working on displaying simple components in AngularJS where the child component needs to access the parent's name. Here is a snippet of my code: Here is my HTML file: <html> <head> <script type='t ...

What is the process for deleting a token from local storage and displaying the logout page in Next JS?

I developed a Next.js web application and am looking to display a logout page when the token expires, while also removing the expired token from local storage. How can I ensure that this functionality works no matter which page the user visits within the a ...

Issue with Bootstrap 4 Grid Layout System

Recently delved into the world of Bootstrap 4 and its responsive grid system. Everything seemed to be going smoothly with my columns and resizing windows, until I encountered an issue on xs screensize where all columns automatically spanned 12 instead of ...

Utilizing Vue JS for applying multiple filters on a single array

I'm currently facing challenges in optimizing my code. I've successfully created dynamically generated objects from an array, implemented a search function, and had a working filter (just one) at some point. However, my attempt to chain the filte ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...

Prevent TypeScript from generalizing string literals as types

I have a constant Object called STUDY_TAGS with specific properties const STUDY_TAGS ={ InstanceAvailability: { tag: "00080056", type: "optional", vr: "string" }, ModalitiesinStudy: { tag: "00080061", type: " ...

Retrieving Blocked Images with Selenium: A Step-by-Step Guide

HTML: <html> <head> <body onload="document.getElementById('a').style.display='block';"> <div id="a" align="center" onclick="document.location.reload();" style="display: block; cursor: pointer;"> <img width="9 ...

Exploring ways to cycle through dynamically loaded checkboxes with AJAX?

I'm looking to apply a similar function to checkboxes that are loaded dynamically via AJAX: $('input:checkbox').each(function() { $(this).hide(); alert("hi"); $('<div class="checkbox-fx"><div class="che ...

Update the text box with the value of the checkbox selected before

<!doctype html> <html lang="en"> <head> <meta charset="UTF-8> <link rel="stylesheet" href="ios7-switches.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <styl ...