1

I have a modal which I call from a function, when I call the modal I want to pass a URL to it like so:

ng-click="showModal('abc','testUrl')"

I want to share testUrl between controllers so I'm trying this:

hmwsApp.controller('mainController', ['$scope', '$http', '$rootScope', 'ModalService', function($scope, $http, $rootScope, ModalService) {

$scope.showModal = function(modalUrl, imageUrl) {
  $rootScope.$broadcast('imageUrl', imageUrl); // <--- set global scope var
  ModalService.showModal({
    templateUrl: '/views/modals/' + modalUrl + '.html',
    controller: "ModalController"
  })
  .then(function(modal) {
    modal.element.modal();
    modal.close.then(function(result) {
      $scope.message = "Image show " + result;
    });
  });
};

}]);

Then in modal controller:

hmwsApp.controller('ModalController', function($scope, close) {

$scope.$on('imageUrl', function(response) {
  $scope.imageUrl = response; // <--- read global scope var
})

$scope.close = function(result) {
    close(result, 500); // close, but give 500ms for bootstrap to animate
};

});

The reason I'm doing this is I want to reference the URL in the modal like so:

<div class="modal-content">
  <img src="{{ imageUrl }}">
</div>

But it simply doesn't work, the img src is empty, so I guess I'm missing something but not sure what? Any ideas?

UPDATE

Also tried the following but still nothing:

$scope.$on('imageUrl', function(events, args){
  console.log(args); // <--- empty
  $scope.imageUrl = args;
});
StudioTime
  • 22,603
  • 38
  • 120
  • 207

1 Answers1

1

From what I can see, your ModalController isn't instantiated when you do the $rootScope.$broadcast call. You should do it AFTER you've shown the modal, otherwise it won't be "in existence" to intercept it with $scope.$on

Ben Black
  • 3,751
  • 2
  • 25
  • 43