0

I faced the same issue as asked here, And the solution worked too. But could not wrap my head around when are the scopes created. If new scope is created on $modal directive in below code, then why scope in modal.html(view) and ModalInstanceCtrl different ?

In the below piece of code from same question :

$scope.open = function () {
    var modalInstance = $modal.open({
      templateUrl: 'modal.html',
      controller: 'ModalInstanceCtrl'
    });

(The main problem was in modal.html the ng-model="text" was not in the same scope object as $scope in its controller : ModalInstanceCtrl.)

What I understand about scopes is that the rootscope is first created by ng-app. Then new scopes are created by directives that create new scopes.

The main discrepancy was that in routing, the structure is similar to above code :

 $routeProvider
    .when('/', {
      redirectTo: '/pages'
    })
    .when('/food', {
      templateUrl: 'food.html',
      controller: 'foodController'
    })
    .when('/play', {
      templateUrl: 'play.html',
      controller: 'playController'
    });

In spite of similarity, here the scope object in templateUrl(view) and controller is same, so why in fisrt code the scope in templateUrl(view) and controller are different ? In referenced question, the comment in answer was that its due to nested controllers, I see that in second piece of code no nesting of controllers is there while in first one there is. But this does not clear that why in first piece of code, the scope in view and controller are different, and when is new scope created.

Community
  • 1
  • 1
Anubha
  • 1,345
  • 6
  • 23
  • 35

1 Answers1

3

Reoccuring WTF when writing angular apps. When this happens to me I get that gut feeling that there is a "hidden" scope being used somewhere and I probably forgot the "prefer dot notation in ng-model" rule.

In this case, look at the html source. Your modal.html content is inside a <div class="modal-content" ng-transclude>. This binds to a new transcluded scope that inherits from ModalInstanceCtrl's scope.

When you type into input, a new text property is added to the transcluded scope because assignment of primitives directly on a scope does not consult the prototype chain. ModalInstanceCtrl's scope is not consulted.

Assignment of primitives to objects on the scope does consult the prototype chain, hence the use dot notation rule. That is why your referenced SO article works with input.abc

Here is a great SO article on prototypical inheritance and angular scopes

Community
  • 1
  • 1
Matthew Petty
  • 652
  • 5
  • 7
  • Oh...so here, the ng-transclude directive is culprit creating the new scope. One more thing I would like to clear, Is $scope of ModalDemoCtrl same as $scope of ModalInstanceCtrl ? (in the question I referenced) – Anubha Feb 08 '14 at 12:21
  • No. They are different. – Matthew Petty Feb 08 '14 at 17:48