stefanz stefanz - 2 years ago 131
AngularJS Question

How to extend/overwrite default options in Angular Material $

TL;DR : I need a way to overwrite default options provided my Angular Material (especially on Material Dialog) using providers (like any other angular modules - a random example).

I have been looking for a way to customize defaults options Angular Material Modal but without any usable result.

Like I have used on other plugins/modules this way could be achieved using a

. Having a look in the core of the material (1.0.8) I was trying to set options using
method like this (let say I just want to disable backdrop for moment):

app.config(['$mdDialogProvider', function($mdDialogProvider){
// ^ $get/addMethod/addPreset/setDefaults

var defaults = {
options: function(){
return {
hasBackdrop: false

Right now when I am checking the options on
callback :

enter image description here

So as you can see the
option is updated, but the modal is not working anymore so I think I am missing something.

Do you have any idea how the angular defaults could be extended in a proper way?


UPDATE : Options object without having
active (de initial state)

enter image description here

Note : I have copied from their core
and added in my defaults object, but the result is the same. I can see the DOM updated, console has no errors, but the modal is not visible.

Answer Source

When you want to update an existing functionality from a third party library, you should try to use decorator pattern and decorate the service method.

Angular provides a neat way of doing this using decorators on providers while configuring the app:$provide


$provide.decorator(name, decorator);

Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behavior of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.

You can write a decorator for $mdDialogProvider to extend the functionality of the .show method and pass it the extended options object like shown below:

.config(function ($provide) {
  // Decorate the $mdDialog service using $provide.decorator
  $provide.decorator("$mdDialog", function ($delegate) {
    // Get a handle of the show method
    var methodHandle = $;

    function decorateDialogShow () {
      var args = angular.extend({}, arguments[0], { hasBackdrop: false })
      return methodHandle(args);

    $ = decorateDialogShow; 
    return $delegate;

I have created a codepen with a working example with { hasBackdrop: false } so that backdrop is not shown on calling $

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download