Is the $scope object shared among all controllers in AngularJS when nested controllers are used?

Is it possible to use nested controllers in AngularJS? When using nested controllers, is the $scope object shared across all controllers?

The issue at hand is:-

While I can access the $scope values of the first controller across all controllers, I am unable to retrieve the scope objects of the second controller in the third controller. You can test this using the snippet provided below.

 var app = angular.module("appTest",[]);


    function Controller1($scope) {
      $scope.text1= "Sample Text 1"
    }

    function Controller2($scope) {
      $scope.text2= "Sample Text 2"
    }
    
    function Controller3($scope) {
      $scope.text3 = $scope.text1 + " And " + $scope.text2;
    }

    app.controller("Controller1",Controller1);
    app.controller("Controller2",Controller2);
    app.controller("Controller3",Controller3);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="appTest">
    <div ng-controller="Controller1">
      <div>
      <h1> First Controller</h1>
        Values in the First Controller are <b> {{text1}}</b>
      </div>
      <div ng-controller="Controller2">
       <h1> Second Controller</h1>
        Values in the First Controller are <b> {{text1}}</b>
        <br />
        Value in the Second Controller is <b> {{text2}}</b>
      </div>
       <div ng-controller="Controller3">
       <h1> Third Controller</h1>
        Combination of values from First Controller and Second Controller is <b> {{text3}}</b>
       
      </div>
    </div>
  </body>

Answer №1

Absolutely, in angularjs you can definitely have nested controllers. The scope of the parent controller will trickle down through the prototypical chain, allowing all child controllers to access the parent's scope.

However, there seems to be an issue with accessing the scope objects of the second controller from the third controller.

The reason for this is that the third controller operates independently from the second controller. Directly accessing the $scope property of another independent controller is not supported. To resolve this, you can either nest the third controller within the second one, or alternatively, utilize a service to facilitate data sharing (the latter is the preferred approach).

var app = angular.module("appDemo",[]);


    function ParentController($scope) {
      $scope.text1= "Sample Text 1"
    }

    function SecondController($scope) {
      $scope.text2= "Sample Text 2"
      $scope.text1="Sample Text 1 accessed from second controller";//this will be visible in second controller and to access parent data, you can use $parent
    }
    
    function ThirdController($scope) {
      $scope.text3 = $scope.text1 + " And " + $scope.text2;
    }

    app.controller("ParentController", ParentController);
    app.controller("SecondController", SecondController);
    app.controller("ThirdController", ThirdController);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="appDemo">
    <div ng-controller="ParentController">
        <div>
            <h1> Parent Controller</h1> Value in Parent Controller is <b> {{text1}}</b> </div>
        <div ng-controller="SecondController">
            <h1> Second Controller</h1> Value from Parent Controller is <b> {{$parent.text1}}</b>
             Value of Parent Controller's scope object in the second controller is <b> {{text1}}</b>
            <br /> Value in second controller is <b> {{text2}}</b>
            <div ng-controller="ThirdController">
                <h1> Third Controller</h1> Combined values from Parent and Second controller is <b> {{text3}}</b> </div>
        </div>
    </div>
</body>

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

Load the entire AngularJS webpage using AJAX requests

I'm facing a challenge where I need to integrate an entire legacy page, along with some AngularJS elements, into our new page using AJAX. Initially, all I could see was the raw AngularJS markup: Rank ID {{$index+1}} {{player.playerid}} Afte ...

Ways to enlarge a YouTube thumbnail upon loading using JavaScript

I recently found a solution to my question on how to prevent YouTube videos from repeating even when different embedded codes are used. I have a specific need to resize the thumbnail image of my YouTube video to width:146px and height:124px when the page l ...

Ways to change object to string in javascript

My object has the following structure: Object {Dry Aged Ribeye(medium): "1" , Dry Aged Ribeye(rare): "1" , Dry Aged Ribeye(well): "1" , favorite_tables: "{"dc76e9f0c0006e8f919e0c515c66dbba3982f785":[]}" } I am trying to insert this into My ...

Personalized HTML characteristics

Within the realm of AngularJS (and possibly jQuery UI), I've come across tags such as ui:some_random_name and ng:some_random_name. It seems that according to the HTML specification, non-standard attributes are not allowed. So how do these libraries m ...

axios: prevent automatic sorting of objects according to keys

When using axios, I am receiving an API response. To send the sorted API response based on name, I use the following endpoint: http://localhost:8000/api/ingredients/ordering=name The actual object received from my server looks like this: { 2:{"id":2 ...

What are the differences between a Chrome app and extension? Is there any other way to access the tabs currently open in your

I need to develop an app that can access the tabs a user has open, but I'm struggling to find a way to do so without having my app run in Chrome itself. Creating an extension restricts the UI significantly, which is problematic since my app requires a ...

How can I turn off the animation for a q-select (quasar select input)?

I'm just starting out with Quasar and I'm looking to keep the animation/class change of a q-select (Quasar input select) disabled. Essentially, I want the text to remain static like in this image: https://i.stack.imgur.com/d5O5s.png, instead of c ...

Steps for constructing an object containing an array of nested objects

I've been working on this problem for some time now, and it's starting to feel like a messy situation that just won't come together. I'm trying to recreate an object with 5 properties and a nested array of objects, but so far, it's ...

Easily validating forms using javascript

I'm attempting to design a basic HTML form and would like to implement javascript for validating the input values. Below is the form tag: <form action="" onSubmit="return formValidation();" method="Post" name="form"> Here is a section of the ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

Top recommendation for showcasing a numerical figure with precision to two decimal points

Within my function, I am tasked with returning a string that includes a decimal number. If the number is whole, I simply return it as is along with additional strings. However, if it's not whole, I include the number along with the string up to 2 deci ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Trigger a series of functions upon clicking with ReactJS

Need some assistance with an alert message functionality. I have a button labeled Checkout, and when clicked, it should clear the cart and display an alert. At present, the individual functions work as expected - calling emptyCart() works fine, and calling ...

Is it possible to retrieve data from multiple controllers and send it to the server using AngularJs?

I have multiple controllers and I need to retrieve data through these controllers. Ultimately, I want to post this data into the database server. Below is the code snippet which includes the service and controller that I am currently using. However, I am ...

What are some ways to streamline and improve the readability of my if/else if statement?

I've created a Rock Paper Scissors game that runs in the console. It currently uses multiple if/else if statements to compare user input against the computer's selection and determine a winner. The code is quite lengthy and repetitive, so I' ...

Retrieve the original state of a ReactJs button from the database

I am completely new to ReactJs and I have a question regarding how to set the initial state of a button component based on data from an SQL database. I am successfully retrieving the data using PHP and JSON, but I am struggling with setting the state corre ...

Terminate the JWT token and automatically log out the user in the event of a banning or modification

Greetings fellow developers, I've been working on enhancing my application's user system to include functionality for administrators to upgrade an account's level (granting admin privileges if it reaches level 10) or ban users from the site ...

Assign the two values to variables in the CSS script

My challenge lies in passing two values to the CSS within the <style> tags. The values are: (background-color: --placeholder; color: --placeholdtext;). I am able to pass either one of the values successfully, but not both at the same time. When I cop ...

Unable to locate the React Native variable named "NetworkStatus"

I have been working on implementing a code to test internet connectivity using react native NetInfo from '@react-native-community/netinfo'. Unfortunately, I keep running into an error that says "Can't find variable: connectionStatus&quo ...