angular ui modal can NOT refer to parent scope

All we need is an easy explanation of the problem, so here it is.

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?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Method 2

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;
    }
  }
});

Method 3

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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply