Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Two way binding between controllers in Modal

My index.html contains a contenteditable div and a button. On button click(ng-click) the $uibModal.open() function in the ModalDemoCtrl controller opens a modal window, which then calls the controller ModalInstanceCtrl which renders various smileys in the modal. I want that when I click on a smiley in the modal window, the image gets rendered in the contenteditable div in my index.html

index.html:

<div ng-controller="ModalDemoCtrl" id="angularData">
  <div id="view1">
      <button type="button" class="btn btn-default" ng-click="open('lg')">Emojis</button>
      <div contenteditable="true" ng-model="textModel"></div>
  </div>
</div>

emojis.js:

angular.module('ui.bootstrap.demo')
.controller('ModalDemoCtrl', function ($scope, $uibModal, $log) {

  $scope.animationsEnabled = true;
  $scope.textModel = "Hello";

  $scope.open = function (size) {
    var modalInstance = $uibModal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'template/template.html',
      controller: 'ModalInstanceCtrl',
      windowClass: 'large-Modal',
    });
  };
});


angular.module('ui.bootstrap.demo')
.controller('ModalInstanceCtrl', function ($scope, $window, createEmojiIcon) {

  $scope.getUnicode = function(id) {  //This functions get the img tag of clicked smiley in variable 'input'
  var style = createEmojiIcon.createEmoji(icons[id]);
  var input = '<img src="img/blank.gif" class="img" style="' + style + '" alt="' + icons[id][3] + '" title="' + icons[id][3] + '">';
  }
});

All I want is this variable called input to render in the contenteditable div when the function $scope.getUnicode is called.

In simple words that textModel in the ModalDemoCtrl gets appended with the img tag when the function $scope.getUnicode is called.

ps: The function $scope.getUnicode is called by ng-click in template.html

Here is plunker sample.

like image 551
iamsaksham Avatar asked Mar 17 '26 16:03

iamsaksham


1 Answers

You need to rootScope broadcast for the click event since you have 2 independent scope.

Fixed you code. Passing X from model pop-up to other controller via $rootScope broadcast.

inside ModalInstanceCtrl

$rootScope.$broadcast('selectedCode', {message: 'x'});

And at ModalDemoCtrl

$rootScope.$on('selectedCode', function(event, args){
   alert(args.message);
});

https://plnkr.co/edit/YE3u8JEXJ4mABOPhUJyg

like image 117
Dhiren Avatar answered Mar 20 '26 04:03

Dhiren



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!