5

according to the https://angular-ui.github.io/bootstrap/#/modal, I want to pass a result from modal to the parent without closing but in the example code, they only show a passing result to parent via closing

$uibModalInstance.close($scope.selected.item);

I want to pass a data to parent when the item is clicked but I do not know to do it. I really need help. Thanks.

Hikaru Shindo
  • 2,611
  • 8
  • 34
  • 59

2 Answers2

3

This is a quite common problem about communicating between controllers since you don't want to close the model and wants to pass the data to a different controller.

The quickest path to your problem is using $broadcast. In the controller of your modal, write like this:

// Make sure to use $rootScope
$rootScope.$broadcast("modalDataEventFoo", {selectedItem: $scope.selected.item});

Now, in your parent controller:

$scope.$on("modalDataEventFoo", function(event, data) {
     console.log("got the data from modal", data.selectedItem);
});

Other references for communication between controllers:

  1. What's the correct way to communicate between controllers in AngularJS?
  2. https://egghead.io/lessons/angularjs-sharing-data-between-controllers
  3. http://www.angulartutorial.net/2014/03/communicate-with-controllers-in-angular.html
  4. Communication between controllers in Angular
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
  • Note that the arguments passed to the listener function are: (event, data) and not just (data) as shown in the example above. – Charlie Hills Jan 28 '18 at 14:22
1

Another way is to share the scope between the parent controller and the modal controller declaring scope property in the options:

var modalInstance = $uibModal.open({
  animation: $scope.animationsEnabled,
  templateUrl: 'myModalContent.html',
  controller: 'ModalInstanceCtrl',
  size: size,
  scope: $scope,
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});

Check this plunker in which the modal contains an input element bound to the variable $scope.shared.name: http://plnkr.co/edit/4xiEXATxAnvDKBSXxzQd

beaver
  • 17,333
  • 2
  • 40
  • 66