Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular ui modal can NOT refer to parent scope

i am using angular ui modal to create modal in my project.

Everything works fine until I need to refer to variable in parent scope. see plunker code

It seems like modal can't access parent scope. Is there anyway to overcome this?

like image 802
fuyi Avatar asked May 21 '14 10:05

fuyi


3 Answers

Angular UI's modals use $rootScope by default (See the documentation here).

You can pass a scope parameter with a custom scope when you open the modal – e.g. scope: $scope if you want to pass the parent scope. The modal controller will create a sub-scope from that scope, so you will only be able to use it for your initial values.

like image 54
lyschoening Avatar answered Oct 24 '22 07:10

lyschoening


You'll need to refer to the parent scope in your $modal options. Angular documentation

Corrected Plunker Version

Below is also a code snippet of what I added to make it work.

var modalInstance = $modal.open({
  templateUrl: 'myModalContent.html',
  controller: ModalInstanceCtrl,
  scope:$scope, //Refer to parent scope here
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});
like image 31
Shaidar Avatar answered Oct 24 '22 07:10

Shaidar


You can add an ID to the parent div and use his scope.

<div id="outerdiv"  ng-controller="OuterCtrl">
<h2>Outer Controller</h2>
<input type="text" ng-model="checkBind">
<p>Value Of checkbind: {{checkBind}}</p>

And set up a "fake" binding within the controller

//init
$scope.checkBind = angular.element(document.getElementById('outerdiv')).scope().checkBind;

  $scope.$watch('checkBind', function (newValue, oldValue) {
//update parent
  angular.element(document.getElementById('outerdiv')).scope().checkBind = $scope.checkBind;
  });

See http://plnkr.co/edit/u6DuoHJmOctFLFhvqCME?p=preview

like image 37
BironDavid Avatar answered Oct 24 '22 08:10

BironDavid