Search code examples
angularjsangularjs-components

How to handle dialogs in Angular component-based architecture


I'm working on an application in Angular 1.5. I stick to Component-based architecture (https://docs.angularjs.org/guide/component) and Input/Output flow described there.

Until now it worked fine, but now i need to open a child component as a dialog window and I'm stuck.

The architecture is fine when you render components tree down starting from main component. But i don't have an idea how get one of those children and display it as a dialog, and still use recommended Input/Output flow.

Do You know any pattern/library to do so?


Solution

  • The library would be angular material:

    https://material.angularjs.org/latest/demo/dialog

    The pattern would have to be something like this:

    // my-dialog.js
    'use es6'
    export default locals => ({
      locals, // will be bound to the controller instance!
      template:
    `
    <p>Something: <span>{{$ctrl.foo}}</span></p>
    <md-button ng-click="$ctrl.onSave()">Save</md-button>
    <md-button ng-click="$ctrl.cancel()">Cancel</md-button>
    ` ,
      bindToController: true,
      controllerAs: '$ctrl',
      controller: function($mdDialog, myService) {
        // this.foo = ..will be provided in locals as an input parameter..
        // this.onSave = () { ..will be provided as output parameter.. }
        this.cancel = () => {
          $mdDialog.cancel()
        }
      },
      clickOutsideToClose: true
    })
    

    Wich you would invoke from the parent component like this:

    // main-component.js
    'use es6'
    import myDialog from './my-dialog'
    ..
    $mdDialog.show(myDialog({
      foo: 'bar',
      onSave: () => { .. }
    }))
    

    Hope this helps!