0

Best explained with a couple fiddles. I'm using these simple directives in both:

var demo = angular.module('demo', []);

demo.directive('redBox', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div class="bg-red size-med"><b>I am inside a red box.</b><div ng-transclude></div></div>'
    }
});

demo.directive('blueBox', function() {
    return {
        restrict: 'E',
        replace: false,
        transclude: true,
        template: '<div class="bg-blue size-med"><b>I am inside a blue box.</b><div ng-transclude></div></div>'
    }
});

function MyCtrl ($scope) {  

};

I include both of these and print the scope ids in Fiddle #1. This works as I expect - the scopes of both redBox and blueBox are children of MyCtrl's scope.

<div ng-app='demo'>
    <div ng-controller='MyCtrl'>
        My scope's id is {{$id}}.  <br/>  My parent scope's id is {{ $parent.$id }}. 

        <red-box>
            My scope's id is {{$id}}.  <br/>  My parent scope's id is {{ $parent.$id }}.
        </red-box>

        <blue-box>
            My scope's id is {{$id}}.  <br/>   My parent scope's id is {{ $parent.$id }}.
        </blue-box>
    </div>

</div>

In Fiddle #2, I simply add a tag in the content of one of the divs. This changes the scope hierarchy! Even though they are not nested, the scope of one directive is the parent of that of the other.

What's going on here? How could this change the parent-child relationship of the scopes?

Jer
  • 5,468
  • 8
  • 34
  • 41

1 Answers1

2

In Html5 <p /> means <p>, because <p> is not a "self-closing tag".

So, this:

<p/>My parent scope's id is {{ $parent.$id }}.

will be interpreted by your browser like this:

<p>My parent scope's id is {{ $parent.$id }}.</p>

You may want to have a look at this question.

Community
  • 1
  • 1
Josep
  • 12,926
  • 2
  • 42
  • 45
  • Thanks @Josep, very useful for a (relative) beginner. Also, I may as well point out that one of my pet peeves is when people make snarky comments on questions from people who are clearly just trying to learn. And also when they don't know how to spell "pet peeve." – Jer Oct 24 '14 at 16:02