Audrey Audrey - 28 days ago 6
HTML Question

AngularJS $uibModal as a service with different controllers

I'm sitting with this question for a while.

I'm wondering how you can add different kind of controllers and different templateUrl from angularjs to

$uibModal
. So that You don't have that much code that actually does the same thing. Only on different
controller
and different
template
.

This is what I have done so far:





vm.addDialogue = function () {
vm.formData = {};

var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'views/modals/add.dialogue.html',
controller: 'addDialogueController',
controllerAs: 'vm',
backdrop: 'static',
resolve: {
formData: function() {
return vm.formData;
},
selectedTab: 1,
editTime: false
}
});
};

vm.addProject = function(){
vm.formData = {};

var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'views/modals/add.project.html',
controller: 'addProjectController',
controllerAs: 'vm',
backdrop: 'static',
resolve: {
formData: function () {
return vm.formData;
}
}
});

modalInstance.result.then(function (newProject) {
vm.errorMessage = null;
vm.projects.unshift(savedProject);
}, function () {
console.info('Modal dismissed at: ' + new Date());
});
}





This works but I have five more of these Modals, I'm trying to find something that these seven fit in one function and not seven different functions.
I have also tried putting this all in once controller instead of the controllers they belonged in. That worked for a moment but then it didn't showed some buttons that were supposed to be on a page.

lin lin
Answer Source

Well, you could abstract your code by using a service and parse your params into. This service will handle the uibModal instance. In that way you could avoid your duplicate code.

AngularJS example application & service:

var myApp = angular.module('myApp', []);

//simple controller
myApp.controller('MyCtrl', function (myModalService) {

  //open modal
  myModalService.openModal('views/modals/add.project.html', 'addProjectController');

  //close on click
  $scope.close = function () {
      myModalService.modalInstance.close();
  }
});

// my simple modal service
myApp.service('myModalService', function() {

  this.modalInstance = null;

  this.openModal = function (templateUrl, controller) {

    this.modalInstance = $uibModal.open({
      animation: true,
      templateUrl: templateUrl,
      controller: controller,
      controllerAs: 'vm',
      backdrop: 'static',
      resolve: {
        formData: function() {
          return vm.formData;
        }
      }
    });

    return this.modalInstance;
  }

  return this;
});