Access scope variable in AngularJs from another scope variable

I am currently working on a basic app for demonstration purposes, and I have encountered the following issue: I have two objects in my controller (credentials and authServer) and I want to access the properties of credentials within the authServer object. The input fields bound to both scope.credential properties do not update when changed in my authServer object.

While I know that I can use $watch to solve this problem, I am seeking a more elegant solution.


var app = angular.module('clientApp', []);
app.controller('myCtrl', function($scope) {
    $scope.credentials = {
      'username': null,
      'password' : null
    };

    $scope.authServer = {
      'url' : 'http://localhost:9000/auth', 
      'request' : {
        'grant_type': null,
        'scope': null,
        'client_id': null,
        'client_secret': null, 
        'username' : $scope.credentials.username,
        'password' : $scope.credentials.password
      }
    };
});

Answer №1

Modify this section as shown below

$scope.authServer = {
  'url' : 'http://localhost:9000/auth', 
  'request' : {
    'grant_type': null,
    'scope': null,
    'client_id': null,
    'client_secret': null, 
    'username' : $scope.credentials.username,
    'password' : $scope.credentials.password
  }
};

It is important to use '$scope.credentials' in the code because objects are passed by reference, while $scope.credentials.username is passed by value.

$scope.authServer = {
  'url' : 'http://localhost:9000/auth', 
  'request' : $scope.credentials
};

$scope.authServer.request['grant_type'] = null;
$scope.authServer.request['scope'] = null;
$scope.authServer.request['client_id'] = null;
$scope.authServer.request['client_secret'] = null;

Answer №2

Method 1

Assign a value to $scope.authServer only when necessary

$scope.doRequest = function() {
  $scope.authServer = {
  'url' : 'http://localhost:9000/auth', 
  'request' : {
    'grant_type': null,
    'scope': null,
    'client_id': null,
    'client_secret': null, 
    'username' : $scope.credentials.username,
    'password' : $scope.credentials.password
  };
  // utilize $scope.authServer in this section
};

Method 2

Implement a

$scope.$watch('credentials', function(){ $scope.authServer=/*...*/ }, true);
inside your controller

Method 3

(Check Yang Li's response), refer to the object $scope.credentials rather than its specific attributes

Answer №3

Make sure to properly assign the credentials object, as it is a reference type. Remember, the username and password are primitives, which are value types.

Check out this Plunker Example for more details.

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
 $scope.credentials = {
      'username': null,
      'password' : null
    };

    $scope.authServer = {
      'url' : 'http://localhost:9000/auth', 
      'request' : {
        'grant_type': null,
        'scope': null,
        'client_id': null,
        'client_secret': null, 
        'credentials': $scope.credentials
      }
    };
});

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

Using AngularJS to modify a record

I am currently developing a web application using C# with angularjs. Within my app, I have multiple records that I need to update. I have set up the necessary web service and included the required JS files for updating these records. My main concern is fig ...

Having trouble with CSS paths in EJS Node.JS Express when dealing with URLs containing multiple parameters?

Apologies for my limited English skills! Currently, I am working on a web application using NodeJS/Express and EJS as the template engine. I have encountered a problem in my development process. Below is the folder structure of my project: App folder/ ...

Reasons for a service not receiving events

I had a piece of code that was functioning well within a controller. I decided to refactor it and move the functionality to a service. The code contained an event listener: $rootScope.$on( .....) Previously, this event was caught when it was in the contr ...

Mongoose's Aggregation feature is encountering issues when using Match and Group functions

I am currently working on developing an application using AngularJS, NodeJS, and Mongoose. I am in the process of creating a chart where I need to retrieve data based on certain parameters. However, I am facing issues with aggregation. The query below is f ...

Switching carousel background image upon navigation click

I am currently working with a Bootstrap Carousel and I want to customize the background (an image) for each slide. I have 4 slides in total, each corresponding to a specific background image. <!DOCTYPE html> <html lang="en" dir="ltr ...

The clientHeight property is yielding a result of zero

I'm using JavaScript to create DOM elements dynamically. In order to animate a slide down effect, I need to retrieve the height of a specific div element. However, both clientHeight and offsetHeight are returning 0. I have confirmed that the div eleme ...

Looking to showcase elements within an array inside an object using ng-repeat

In this JSON dataset, we have information about various anchoring products. These products include anchors, cleats, snubbers, shackles, and more. When it comes to displaying these products on an HTML page using Angular, make sure to properly reference the ...

Material-Table does not allow resizing of columns if there are more than 5 columns present

I'm currently using the material-table library to present my data. Despite my attempts, setting a fixed size for each of my 19 columns isn't working as intended. Using width: 45% doesn't produce the expected visual result. Also, implementing ...

At times, the animation in SetInterval may experience interruptions

I have created an animation using a sequence of images. The animation runs smoothly with the setinterval function, but for some reason, it occasionally pauses. I've shared a fiddle where you can see this pause happening. Click Here to See the Unwante ...

sending data with JavaScript and AJAX to a PHP file

$(document).ready(function() { $(":input").focusout(function () { var a= $(this).closest("tr").attr('id'); var b= $(this).closest("td").attr('id'); var data = $(this).attr("value"); $.post("database.php", {trAdress: ...

Trying to save the array returned from Object.keys(obj) into a variable in JavaScript but encountering the error message "ReferenceError: array is not defined"

I'm struggling with this code and can't seem to figure out what's wrong. For some reason, the line "arrKeys = Object.keys(source);" is not returning the array as expected. function findMatchingValues(collection, source) { var arr = []; ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

Discovering and editing a specific line in Sheets: An in-depth look at the Message Counter

Currently, the bot checks if your ID already exists in the sheet list and adds you if it doesn't when someone writes a message in the chat. Now, I want the bot to implement a message counter in the sheet list. What would be the most effective way to ...

Enabling and disabling multiple input fields based on the status of a checkbox in order to manage dynamic inputs

I need help with a situation involving dynamic input fields and checkboxes. My goal is to disable the input field if the checkbox with the corresponding ID is checked. Here is the PHP code snippet: <table class="table table-striped"> <thead& ...

Creating functionality with a native JavaScript plugin within a directive and test suite

I have a custom JavaScript plugin that is integrated within a directive and utilized in an Angular manner. Snippet of the directive, export default function () { 'use strict'; return { restrict: 'E', scope: { map: &apo ...

Reading data from a Node PassThrough stream after writing has finished can be achieved by piping the stream

Is it possible to write to a Node Passthrough stream and then read the data at a later time? I am encountering an issue where my code hangs when trying to do this. Below is a simplified example in Typescript: const stream = new PassThrough(); strea ...

Results of the Angular Strap typeahead showing in angular brackets

My testing shows that the results display correctly when brackets are included. However, upon closing the brackets, the input value is erased of any content within the brackets. When I type "frank," the output is: frank<hotdog> frankenstein If I ...

JavaScript can extract a portion of an array

Is it possible to generate a new array consisting of all elements ranging from the nth to the (n+k)th positions within an existing array? ...

Customizing the appearance of the Bootstrap Typeahead

I've been experimenting with the Bootstrap Typeahead for my search feature. I successfully implemented the dropdown list using Ajax. However, I am looking to customize the width, padding, and background color of the dropdown menu, which is currently w ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...