以下は、ローカルに保存されている HTML のブロックをスクリプト要素に挿入するために私が書いた簡単なディレクティブです。
使用方法は次のとおりです。
<body>
<div my-partial="partial1"></div>
</body>
<script id="partial1" type="text/html">
<div>
<button ng-click="OK()">OK</button>
</div>
</script>
コードは私が望むことを行いますが、部分的なテンプレートがディレクティブを使用して要素を置き換えると、そのng-scope
上にクラスがあることがわかります。これにより、新しいスコープが作成されたと思われますが、これは私の意図ではありませんでした。HTML を挿入して、既存のスコープの一部にしたかっただけです。
なぜこうなった?
ディレクティブは次のとおりです。
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 <text node>
partial = $("<div>").html(markup); //Stick markup text into a <div> so it'll become real DOM elements
partial = partial.contents(); //Don't need that outer <div> 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;
}]);
ヘルプまたは提案されたコードの改善に感謝します。