kid_drew kid_drew - 4 months ago 44
AngularJS Question

Ionic/AngularJS - global modal with controller

Bare with me - I'm an AngularJS newb.

I have a form that I want to be available from anywhere in my app, and I'm trying to figure out how to code that. My current attempt is to put the modal into a service, like this:

.service('NewObjectService', function() {
var svc = this;

svc.showModal = function() {
$ionicModal.fromTemplateUrl('template.html', {
scope: null, // what should I do here?
animation: 'slide-in-up'
}).then(function(modal) {
svc.modal = modal;
modal.show();
});
}
})

.controller('NewObjectController', function() {
$scope.$on('$ionicView.enter', function() {
console.log('NewObjectController');
// setup new object
})
})


Then from anywhere in my app, I can call
NewObjectService.showModal()
and the modal pops up. That part is working.

The trouble I'm running into is that I can't get my controller to fire, so the initialization never gets called and my new object is null.

It seems like I should actually be calling the modal from within
NewObjectController
to setup scope, but I tried that and I couldn't figure out how to call that controller from within other controllers - hence the service.

I know I'm just doing something fundamentally wrong, but I'm not sure what it is. Any help?

Update: I also just tried calling one controller from another using a root scope broadcast:

.controller('MainCtrl', function() {
this.showModal = function() {
$rootScope.$broadcast('new_object:show_modal');
}
})

.controller('NewObjectCtrl', function() {
$rootScope.$on('new_object:show_modal', function() {
// show modal
})
})


The problem I'm running into there is that NewObjectCtrl hasn't been invoked at the time MainCtrl runs, so it doesn't catch the broadcast event.

Answer

When you declare a service you need to return itself in the Angular declaration ie var svc = {}; return svc; Call svc.showModal from any controller after you've injected the service and pass in the scope. Call the controller from another controller by using $rootScope.$on (receiver) and $rootScope.$emit (from)

.service('NewObjectService', function($ionicModal) {
  var svc = {};

  svc.showModal = function(_scope) {
    $ionicModal.fromTemplateUrl('template.html', {
      scope: _scope, // passing in scope from controller
      animation: 'slide-in-up'
    }).then(function(modal) {
      svc.modal = modal;
      modal.show();
    });
  }

  return svc;

})

.controller('NewObjectController', function($scope, $rootScope, NewObjectService) {
  // fires off when $rootScope.$emit('ShowModal') is called anywhere
  $rootScope.$on('ShowModal', function(data) {
    NewObjectService.showModal(data._scope);
  });
})

.controller('OtherController', function($scope, $rootScope) {
  $scope.contactOtherController = function() {
    // contact the other controller from this controller
    $rootScope.$emit("ShowModal", {scope: $scope});
  }
})
Comments