Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my directive creating a new scope?
    primarykey
    data
    text
    <p>Below is a simple directive I wrote to insert a block of HTML stored locally in a script element.</p> <p><strong>Here's how it's used:</strong></p> <pre><code>&lt;body&gt; &lt;div my-partial="partial1"&gt;&lt;/div&gt; &lt;/body&gt; &lt;script id="partial1" type="text/html"&gt; &lt;div&gt; &lt;button ng-click="OK()"&gt;OK&lt;/button&gt; &lt;/div&gt; &lt;/script&gt; </code></pre> <p>The code does do what I want but I see that when the partial template replaces the element using the directive it has the <code>ng-scope</code> class on it. This makes me think a new scope was created, but this was not my intention. I just wanted the HTML to be insertd and be part of the existing scope. </p> <p><em>Why is this happening?</em></p> <p><strong>Here's the directive:</strong></p> <pre><code> app.directive("myPartial", ["$compile", function ($compile) { var def = { restrict: 'A', scope:false, compile: function (element, attributes, transclude) { var tmplID = attributes.myPartial, //Get templateID markup = $("#" + tmplID).html(), //Load partial template markup &lt;text node&gt; partial = $("&lt;div&gt;").html(markup); //Stick markup text into a &lt;div&gt; so it'll become real DOM elements partial = partial.contents(); //Don't need that outer &lt;div&gt; anymore if (!partial.length) { throw "myPartial: " + tmplID + " not found"; } //Replace this element w/ the partial template markup element.replaceWith(partial); //PostLink //--------------------------------------------------------------------- return function postLink(scope, element, attributes, modelController) { //Compile the partial and link it w/ the current scope $compile(partial)(scope); } } }; return def; }]); </code></pre> <p>Thanks for any help or suggested code improvements.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload