Angularjs 为什么我的指令要创建一个新的范围?
下面是我编写的一个简单指令,用于插入本地存储在脚本元素中的HTML块 下面是它的用法:Angularjs 为什么我的指令要创建一个新的范围?,angularjs,angularjs-directive,angularjs-scope,Angularjs,Angularjs Directive,Angularjs Scope,下面是我编写的一个简单指令,用于插入本地存储在脚本元素中的HTML块 下面是它的用法: <body> <div my-partial="partial1"></div> </body> <script id="partial1" type="text/html"> <div> <button ng-click="OK()">OK</button> </div>
<body>
<div my-partial="partial1"></div>
</body>
<script id="partial1" type="text/html">
<div>
<button ng-click="OK()">OK</button>
</div>
</script>
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;
}]);
感谢您的帮助或建议的代码改进。回答第二个问题: 无法访问编译函数内的作用域。有关详细原因,请阅读Angular.js存储库Wiki中的“”。
只要将这些值定期绑定到您的作用域,并在需要时使用link函数修改作用域。我认为问题与post link函数有关。在这种情况下,我不认为我应该有一个 这似乎有效:
{
restrict: 'A', //Attribute
scope: false, //Don't create a new scope
compile: function(element, attributes, transclude)
{
//Get partial template
var partial = $("#" + attributes.asmPartial);
//Add the partial to the element
element.html(partial.html());
//Remove the element leaving only the partial
element.contents().unwrap();
}
}
当您将scope属性设置为true时就是这种情况,但是您确定scope为false时也是这种情况吗?scope:true=除模板根上的新范围之外的所有指令实例之间的共享范围。您可以在文档中自己阅读(搜索我的引用)。我就是这么理解的,我错了。“scope:false”不创建作用域。查看我的测试:是的,我看到没有在那里创建范围。那么为什么我的指令会创建一个作用域呢?