Sharing information from the $mdDialog child component to the parent component

I have a scenario where I am using one app controller to call a model window and need to pass data from the $mdDialog model window to the app controller. How can I achieve this?

//parent Controller
class appCtrl implements IappSettings {
    public displayItems = [some array items];
    public sortingItems = [some array items];
    public backItems: string;
}

dopopup(event) {
    this.$mdDialog.show({                
        controller: appCtrl,
        controllerAs: '$ctrl',
        template: '<displayArrayCtrl on-save="$ctrl.onSave(displayColumns)"></displayArrayCtrl>'
    });
}

onSave(displayColumns) { //on button click on child controller
  this.backItems = displayColumns; //Using {{$ctrl.keyItems}} in app.html page but it's giving me empty string
}

//Child Controller
class displayArrayCtrl {
    saveData = function (selectedFields: any, sortSelectedFields: any) { //on button click on parent controller
        this.onSave({displayColumns: this.displayColumns}); //calling parent controller event
    }       
}

class displayArrayOptionsOptions implements ng.IComponentOptions {
    public controller: any;
    public templateUrl: string;
    public bindings: any;

    constructor() {
        this.controller = displayArrayCtrl;
        this.templateUrl = 'page.html';
        this.bindings = {
            onSave: '&',
            displayItems: '<',
            sortingItems: '<'
        };
    }

angular.module('app')
  .component('displayArrayCtrl', new displayArrayOptionsOptions());

The communication between the child and parent controllers is working fine, however, there seems to be an issue with how the variable assignment is being handled.

Answer №1

If you want a simple way to retrieve values from a $mdDialog window, just utilize the promise it provides:

var promise = $mdDialog.show({
     controller: function ($scope,$mdDialog) {
          $scope.save = function(data) {
              $mdDialog.hide(data);
          };
     }), 
     template: `
         <div>
             <input ng-model="response" /><br>
             <button ng-click="save(response)">Save</button>
        </div>
     `,
});

promise.then(function(response) {
    console.log(response);
});

For further details, check out

Answer №2

Exploring various methods of communication between a Parent and Child or Child to Parent relationship has led me to the following conclusions:

$broadcast: Used for passing data from Parent to Child components. $emit: Used for passing data from Child to Parent components.

The aforementioned approaches are helpful when dealing with different components and controllers, as simply updating the parent or child scope may not display the desired results.

Utilizing bindings via controller has proven effective in facilitating communication.

Solution:

Incorporate a popup to showcase different components that any controller can utilize:

this.$mdDialog.show({
  scope: this.$scope,
  preserveScope: true,
  bindToController: true,
  template: '<somecomponentname get-back-items="$ctrl.getBackItems"></somecomponentname>'
});

The component "somecomponentname" includes:

constructor() {
  this.controller = someItemCtrl;
  this.templateUrl = 'scripts/somefolder/someitem.html';
  this.bindings = {               
    getBackItems: '='
  };
}

I have defined getBackItems within another controller created within the "somecomponentname" component like so:

public getSelectedFields: any;

Upon closing the popup, assigning values to getBackItemsparent controller

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

Arranging an array in ascending order using Angular JS upon page load

How can I easily organize the following array in ascending order when the page loads: <div ng-init="fruits=['apple','orange','mango','banana','pineapple','kiwi']"> I attempted the followin ...

A step-by-step guide on incorporating MarkerClusterer into a google-map-react component

I am looking to integrate MarkerClusterer into my Google Map using a library or component. Here is a snippet of my current code. Can anyone provide guidance on how I can achieve this with the google-map-react library? Thank you. const handleApiLoaded = ({ ...

Getting the value of the chosen option from one component and passing it to another component in Angular 8

How can I pass the selected option value from the login component to the home component without using local storage? When an option is selected in the login component, I want that value to be displayed in the home component. Below is the code snippet: Lo ...

Unable to load module/controller file from Angular 1 into view/html

var app = angular.module("appModule",[]); app.controller("viewController",function($scope){ $scope.greeting = "Welcome to the future"; }); <html> <head> <script src="Scripts/script.js"></script> <script ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Adding local images to Excel can be easily accomplished using Office Scripts

Hello, I've been attempting to replace Excel cells that contain image filepaths with the actual images themselves. I found an example in Office Scripts that shows how to insert images with online URLs but doesn't mention anything about inserting ...

Unable to navigate to the top of the page after logging in with Angular.js

There is a problem I need help with. After a user successfully logs in and enters the home page, the page automatically scrolls down due to angular.js. I want the page to remain at the top when the user reaches the home page. Can someone assist me in res ...

Passing information from an AngularJS service to a controller

Currently, I am facing a challenge in accessing client-side data through Loopback and the AngularJS SDK. I believe that the issue might be rooted in my lack of experience with Angular, as I am attempting to pass data using an AngularJS controller that invo ...

Issue with TypeORM: The database table is not being created during migration execution in the SQLITE environment

I'm currently encountering an issue with utilizing migrations in TypeORM with a sqlite3 database. My goal is to achieve consistency across different environments (local/testing/staging/production) by only using runtime environment variables that will ...

Troubleshooting issue: Unable to locate library during testing with Nx, Jest, and Angular

In my nx monorepo, I have two apps (client, server) and 5 libraries (client-core, platform-core, etc). To include the libraries in the Angular client application, I set the paths in the tsconfig.json file. "paths": { "@myorg/platfo ...

The TypeScript error ts2322 occurs when using a generic constraint that involves keyof T and a

Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo. const _idKey = Symbol('_idKey') const _sortKey = Symbol('_sortKey') export interface BaseSt ...

I'm curious about what exactly happens when the NextJS Link component is triggered and how we can effectively capture and respond

As I was developing a simple navbar that uses a JSON data to dynamically generate its links, I encountered the need to visually persist the active link/route. To achieve this, I experimented with two different implementations: Initial approach: In the Me ...

"Utilizing the power of Express.js alongside angular.js

angular.module('App').factory('Blogs', ['$resource', function($resource) { return $resource('/api/blog/:blogId/:catId/:search/:pagenum' , { blog: '@blogId', page: "@pageCo ...

Establish a prototype attribute

From what I understand, TypeScript does not make a distinction between prototype properties and instance properties. Additionally, there is no built-in detection for Object.defineProperty on the prototype, which is unlike a feature for typechecking JavaScr ...

Loading Angular2 components dynamically from a module is a powerful feature that allows for greater

Within my Angular application, I have the following setup: export class MyComponent { subcompPath = "path-to-subcomp#SubcompClassName"; @ViewChild("placeholder", { read: ViewComponentRef }) placeholderRef: ViewComponentRef; /* Constructor where C ...

Implement dynamic changes to CSS variable values using Typescript during runtime

My angular 4 web application requires dynamic styling based on color values and image URLs received from the backend. While I have successfully set up the app to load images from the server, handling color values poses a greater challenge. The primary colo ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Exploring the Incorporation of String as a Component Identifier in React and TypeScript

My input component can render either a textarea component (from a library) or a regular input. Check out the code below: import React, { useEffect, useRef, useState } from 'react' import './AppInput.css' interface Props { placehold ...

Tips for utilizing an object key containing a dash ("-") within it

Here is an example of the object structure: { approved_for_syndication: 1 caption: "" copyright: "" media-metadata: (3) [{…}, {…}, {…}] subtype: "photo" } How can I properly a ...

Angular factory transforming service

I am looking to transform the 'i18n' function into a factory in order to return a value instead of just setting it. Any suggestions or tips would be greatly appreciated! services.factory('i18nFactory', function() { var language = ...