How can you interact between a parent's named controller and JavaScript files in AngularJS?

Lately, I've been exploring the use of named controllers in my code and find it to be a much better alternative to using traditional $scope variables. It makes accessing parent controller attributes and functions within the DOM seamless. See an example below.

<div ng-controller="parentCtrl as parent">
    <div ng-controller="childCtrl as child">
        Parent age is {{ parent.age }}
        Child age is {{ child.age }}
    </div>
</div>

I'm now curious about how to utilize the same named controller within the JavaScript file for Angular. Something along the lines of what's shown below.

angular.controller('childCtrl',function(...) {
    var vm = this;
    this.age = 24;
    console.log(parent.age);
});

I understand that the parent needs to be injected before being used. In my current project, I'm working with RequireJS alongside UI Router which eliminates the need for angular.controller and similar constructs. Can anyone provide me with a solution using Plain vanilla Angular or with the help of RequireJS?

Answer №1

One approach I often use is to utilize the $scope variable in order to access the scope of the parent.

app.controller('MainCtrl', function() {
  this.name = 'from parent';
});

app.controller('ChildCtrl', function($scope) {
  this.name = $scope.parent.name;
});

Here is a plunker with the complete example

For a more efficient way to share data between controllers, consider using Angular services. This helps avoid potential issues if the DOM layout is changed or a child controller is moved, as the controllers become independent of the DOM layout.

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 I include multiple dictionary entries in a JSON file at once?

After attempting to include an array with dictionaries in a JSON file, I encountered multiple errors. This has led me to question whether it is feasible to add dictionaries directly into a JSON file without using Node.JS for data insertion. Here is an exa ...

Leveraging trustAsHTML with an array of object elements

I'm facing a challenge in passing an array of objects from an Angular Controller to the ng-repeat directive. The objects within the array have multiple properties, some of which may contain HTML that needs to be displayed using the ng-repeat. I' ...

Attempting to retrieve and substitute the final value within an input field by cross-referencing or evaluating it against a different value

Can you help me with a solution for fetching the last value (word or character) in an input box, storing it in a variable, and then replacing it with one of a set of values that match exactly or partially? The items within the bindname-block contain vario ...

Employing specific delimiters with hogan-express while managing the {{{ yield }}} statement

I've hit a roadblock trying to solve this issue. My goal is to incorporate hogan.js (via hogan-express) into a new expressjs application while also utilizing hogan.js on the front-end with Backbone, lodash, and other tools. The layout I am using cons ...

What methods does Express use to precisely measure time intervals shorter than 1ms?

Recently, I started delving into the world of Express, a web framework for Node.js. While experimenting with it, I noticed that whenever a webpage rendered by Express was refreshed, a series of log messages appeared on my Linux console, as shown below: GE ...

Searching for all potential arrays of length L that total N or fewer can be achieved using an algorithm

In JavaScript, I am looking for a way to discover all potential arrays - consisting of non-negative integers - with a size L that add up to - at most - N: function findArrays(size, maxSum){} For example: findArrays(3, 2) Sample output: [[0,0,0], [0,0,1], ...

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 ...

Leveraging TypeScript enums in conjunction with React to anticipate a string prop

Trying to enforce strict typing for a Button component in React. How can I ensure a prop has a specific string value? The current effort yields Type '"primary"' is not assignable to type 'ButtonLevel' enum ButtonLevel { Primary = ...

Saving a JSON array into separate JS variables using AJAX

I need to extract multiple values from a mySQL Query and store them in different JS Variables. Below is the AJAX code in my JS file: $.ajax({ async:false, url: "get_data.php", type: "POST", data: { d1: 'd ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

After minimizing the window, the jQuery slider animation sped up significantly

I am currently using a coda slider on my website, but I have encountered an issue where the content slider plays too fast after the window is minimized. I believe this may be related to the use of SetTimeout, but I have not been able to find a perfect so ...

Troubleshooting issue: Dexie.js query using .equals not functioning properly in conjunction with localStorage

I am attempting to retrieve a value from indexedDB using Dexie.js, but it seems that the value stored in localStorage is not being recognized. I have tried various methods including async/await, promises, placing the localStorage call in created, mounted, ...

The syntax in JavaScript of (0, fn)(args) is used to call

I came across an interesting piece of JavaScript code in Google's codebase that I wanted to discuss: var myVar = function...; (0, myVar)(args); Do you know what the significance of this syntax is? I'm struggling to see the difference between ( ...

Sending Ajax data to a controller function

I am looking for guidance on how to pass values from my view to my controller using ajax. As someone who is new to working with ajax, I would appreciate some assistance in understanding the process. Full Page @model ALSummary.Models.MonthReport @{ ...

Despite changes in the state they are set to, the InitialValues remain constant

I am facing an issue with a Semantic-UI modal that includes a redux-form as its content. The form is passed to the modal when it opens, and the form element has an initialValues prop mapped to state. <FormModal handl ...

What could be the reason behind TypeScript ignoring a variable's data type?

After declaring a typed variable to hold data fetched from a service, I encountered an issue where the returned data did not match the specified type of the variable. Surprisingly, the variable still accepted the mismatched data. My code snippet is as fol ...

Using jQuery to detect changes in the value of form fields, excluding any changes related to display toggles

Currently, I am in the process of revamping a large form that includes various input fields and dropdown menus. The goal is to submit it via AJAX once a field loses focus but only if the value has been altered. To achieve this, I have set up a jQuery selec ...

JavaScript's Set data structure does not allow for the storage of strings

As I retrieve a collection of data consisting of questions from mongoDB, I am attempting to place them in a random question set. However, the set is not accepting any input and is returning empty. module.exports.java = async (req, resp) => { // const ...

Using Three.js and EffectComposer to create interactive masking with an UnrealBloomPass

Struggling with dynamically masking an UnrealBloomPass using the EffectComposer and encountering unexpected outcomes. Uncertain if missing a crucial concept or exploring the wrong approach. Any insights would be greatly valued. The composer consists of th ...

The babel-preset-es2016 plugin is in need of the babel-runtime peer dependency, however it seems that it

While I am aware that npm no longer automatically installs peer dependencies, why do I still receive a warning after manually installing them? ➜ npm install babel-runtime -g /usr/local/lib └─┬ <a href="/cdn-cgi/l/email-protect ...