Creating a custom mdToast in Angular material with added functionality: A step-by-step guide

Currently, I am working on a project using Angular 1.x and the Material UI framework. While building, I encountered an unusual issue where I am unable to create a custom Toast (snackbar) with functioning buttons:

/// <reference path="../../_All.d.ts"/>

module MbRateDialog {
    class MbRateDialogController {
        static $inject = ['$location', '$scope', '$mdToast']

        constructor(private $location, private $scope, private $mdToast) {
        };

        closeToast() {
          console.log('closed');
          this.$mdToast.hide();
        }

        openToast() {
            this.$mdToast.show({
              hideDelay   : 0,
              position    : 'bottom left',
              autoWrap    : false,
              controller  : 'MbRateToastController',
              template    :
                  `<md-toast class="mb-rate-toast">
                      <div  class="mb-rate-toast__content">
                          <span class="mb-rate-toast__content-text">
                              Heading text
                          </span>
                          <div layout="row" layout-align="space-between center">
                              <mb-button type="primary" ng-click="this.closeToast()">Nope</mb-button>
                              <mb-button type="primary" ng-click="$ctrl.closeToast()">Yup</mb-button>
                          </div>
                      </div>
                  </md-toast>`
            });
        };
    }

    class MbRateDialogComponent implements ng.IComponentOptions {
        public controller = MbRateDialogController;
        public bindings: { [binding: string]: string } = {
            url: '='
        };
        public transclude = true;
        public template =
            `<div flex class="mb-rate-dialog">
                <mb-button type="primary" ng-click="$ctrl.openToast()">RATING</mb-button>
            </div>`;
    }
    angular.module('mbRateDialog').component('mbRateDialog', new MbRateDialogComponent());
}

The main issue I am facing is that the toast buttons are not utilizing the same scope. Initially, I attempted to inject mdToastProvider, however, it resulted in errors. Although the current method works, I am struggling to make the buttons function as intended.

For reference, here is the API documentation for $mdToast: https://material.angularjs.org/latest/api/service/$mdToast

As I am relatively new to Angular, I find myself a bit perplexed by the setup involving controllers for different scopes. Any guidance on this matter would be greatly appreciated. Thank you in advance!

Answer №1

The $mdToast.show method includes a scope parameter which allows you to specify the desired scope.

You have the option to pass in your current scope or create a new scope for reuse.

To create a new scope, you can use the code childScope = $scope.$new();

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

Guide to extracting the outcomes of a promise array and populating them into a new array using Protractor

I am facing a challenge with transferring data from an array of promises generated by the following code: element.all(by.repeater('unit in units')). It seems to be difficult for me to store this data into another array: element.all(by.repeater(& ...

Changing the value of the # in the <mat-menu> tag

I am currently attempting to create a dynamic menu using a JSON blob in my TypeScript files for an Angular project. For this task, I am utilizing the / component from Angular Material. The structure of my JSON menu is as follows: { id: 0, ...

Observing a $scope property of a controller being manipulated by a directive

I am facing an issue with a directive that sets an attribute bound to a controller $scope property, which I have been watching. However, the watcher is never triggered and I'm unclear as to why. Update! The Resolution After investigating further, I ...

What steps are involved in setting up a Restful API using express and node.js?

As a newcomer to node and express, I have been trying to understand how to create a rest API with node. Despite reading some documentation, I am still struggling to grasp the concept. Below is a basic code snippet where I attempt to create a GET API with e ...

The MatFormField component requires a MatFormFieldControl to be present in order to function properly. This error may occur if the

HTML CODE `<mat-form-field> <input type="file" (change)="onFileSelected($event)" name="categoryImage" > </mat-form-field>` TS code onFileSelected(event){ console.log(event);} Encountering an error even before beginning the ope ...

Ways to evaluate a date against a string in JavaScript

I am currently working on developing a custom filter to showcase the most recent file in my system using AngularJS for data filtering. The challenge I am facing is that the date information is saved as a string in my json file, and I'm unsure how to ...

Extracting information from console output and displaying it in a table with angular2

https://i.stack.imgur.com/BMt6J.pngI am facing an issue with retrieving data from the console output and populating it into an HTML table. Can someone please assist me with this? Here is the HTML Code: <table class="table"> <tr> <t ...

Is it possible to enhance an external class with a non-static method using prototypes?

Is it possible to use prototypes to add a function for a class instance? allowing me to access this or __proto__ keyword inside my method, like so: class PersonClass { name: string; constructor(name: string) { this.name = name; } sayHello() ...

Typescript causing undefined React Router match issue

Currently, I am working on a basic eCommerce Proof of Concept using react and TypeScript. Unfortunately, I am facing an issue where I am unable to pass props to a product detail page or access the match containing the params. This is how my Routes pages a ...

I need assistance with using the angular-oauth2-oidc library to retrieve data from an asynchronous storage provider and then pass it to a synchronous storage implementation

Typically, the angular-oauth2-oidc library saves tokens in session storage by default. While you can provide your own storage provider through the OAuthStorage class, it requires a storage provider that can retrieve data synchronously. I am developing a ...

Personalize and modify Ngx-toastr in Angular 6 using TypeScript

Hello everyone, I am currently working on implementing Ngx-toastr in Angular 6 with Typescript. My main issue is that I am struggling to achieve the desired visual appearance because I'm uncertain about which CSS styles are overriding the ngx-toastr c ...

Breaking down an object using symbols as keys in Typescript

I'm encountering an error when running this code Type 'symbol' cannot be used to index type '{ [x: string]: string; }'.: let symbol = Symbol() let obj = { [symbol] : 'value'} let { [symbol]: alias } = obj // ...

What types should be used when passing a NgRx Action as a parameter to a function?

Within my Effects function, I have implemented the following code structure. I have included a few lines of code for the catchError block to ensure that: Any errors are handled by the state/store The errors are forwarded to the global error handler / Int ...

I am interested in showcasing a distinct screen layout specifically designed for mobile device viewing

Looking to display different screens for PC and smartphone users. I am using react, Typescript, and next.js for development. Specifically, I need to show user.tsx when accessing the /user URL from a PC, and Accessdenied.tsx when accessing it from a smartp ...

Encountering a "is not a function" error in NextJS while attempting to import a custom hook

Exploring the world of NextJS, I am embarked on creating a responsive website starting with a navigation bar component. The goal is to ensure that it adapts seamlessly to different viewport dimensions. Let me walk you through my current folder structure: h ...

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

Error: Your call to the "useFormState" function does not match any available

I am fairly new to web application development and I'm facing an issue with the useFormState function. I am currently working on building an edit form for database entries, but the code that previously worked is now throwing an error stating that ther ...

Linking dynamic data to ng-model of a checkbox within an ng-repeat loop

In my controller, there is an array of objects structured like this: this.set = [{ "display": "Name", "pass": "name" }, { "display": "Subject", "pass": "subject" }, { "display": "Batch", "pass": "batch" }]; Checkboxes for name, ba ...

Service in Angular2 designed to retrieve JSON data and extract specific properties or nodes from the JSON object

Currently, I am trying to teach myself Angular2 and facing some difficulties along the way. I am working on creating a service that loads a static JSON file. Right now, I am using i18n files as they are structured in JSON format. The service will include a ...

Tips on incorporating an Electron <webview> tag with TypeScript

When starting my module, I include declare module 'react' { namespace JSX { interface IntrinsicElements { webview: Electron.WebviewTag } } } then in my render method: render() { const {classes: c} = this.props retu ...