Any problem with how I'm creating a modal from a service?


#1

I have a modal that I want to be able to have displayed from any view within my Ionic App… so I put the modal logic into a service. The obvious problem is that the service will need access to the current $scope. I obviously don’t want to have to register the current $scope on every view-change. What I came up with works just fine, but I wanted to know if anyone saw any problems with it…

SyncService.prototype.showInfo = function(){
    var self = this;

    this.$ionicModal.fromTemplateUrl("modules/sync/sync-info-modal.html", {
        scope: angular.element( document.getElementsByTagName('ion-content')[0] ).scope()
    })
    .then( function( modal ){
        self.syncModal = modal;
        self.syncModal.show();
    });
}


SyncService.prototype.hideSyncModal = function(){
    if( this.syncModal ){
        this.syncModal.hide();
        this.syncModal.remove();
    }
}

… the scope line in particular is what I am curious about. I figured there should always be at least one ion-content… Thanks!


#2

If you need a scope and you need a dom element (like ion-content and you are using the ugly hack to use ordinary javascript-selectors instead of angular.element) -> you are forced to implement a directive for that.

Directives -> Dom Manipulation on a single part of the page (so you can not select everything in the dom -> so you can only break one part in the worstcase).

put your directive on the dom-element you want -> in your directive you can build the modal with its own scope and add show and hide functions to that scope.

But an easy way would be to add an parent state to all other states. -> in this state you create the modal and put it on the rootScope -> your hideSyncModal is unnesessary. Because your modal can be called from everywhere so you do not need to build it and remove it. Reuse it!
Create your modal at the app start -> put it on rootscope.

The other controllers can use $rootScope.syncModal.show(), $rootScope.syncModal.hide().