rob*_*rob 14 html javascript angularjs angularjs-directive
有没有办法在不添加额外元素的情况下将某些内容转换为指令.
例如
指示:
{
scope: {
someParam: "="
},
link: function(scope, element, attrs){
//do something
},
transclude: true,
template:'<div ng-transclude></div>'
}
Run Code Online (Sandbox Code Playgroud)
源码html:
<div my-directive some-param="somethingFromController">
my transcluded content: {{somethingElseFromController}}
</div>
Run Code Online (Sandbox Code Playgroud)
在这个例子中,额外的div被添加到标记中.通常情况下这样会很好,但我正在尝试在表中使用此指令,因此添加div标签会搞砸.
我也尝试不指定transclude或template删除额外的div标签,但现在{{somethingElseFromController}}无法找到,因为"transcluded"内容是在一个孤立的范围内.我知道我可以从链接函数中的attrs对象获取我的指令的参数,而不是创建一个隔离的范围,但我宁愿避免需要用范围来计算字符串.$ apply().
有谁知道怎么做到这一点?谢谢!
@Vakey回答的是我在寻找的东西.
但就像今天一样,Angular的文档说:
传递给
compile函数的transclude函数已弃用,因为它不知道正确的外部范围.请使用传递给链接函数的transclude函数.
所以我使用了controller(目前)及其$transclude功能,作为$ compile文档中显示的示例的一部分:
controller: function($scope, $element, $transclude) {
var transcludedContent, transclusionScope;
$transclude(function(clone, scope) {
$element.append(clone);
transcludedContent = clone;
transclusionScope = scope;
});
},
Run Code Online (Sandbox Code Playgroud)
这实际上可以使用Angular.诸如ng-repeat之类的指令就是这样做的.这是你如何做到的:
{
restrict: 'A',
transclude: true,
compile: function (tElement, attrs, transclude) {
return function ($scope) {
transclude($scope, function (clone) {
tElement.append(clone);
});
};
}
};
Run Code Online (Sandbox Code Playgroud)
那么这里发生了什么?在链接期间,我们只是将克隆(我们试图转换的元素)附加到指令的元素中.Angular会将$ scope应用于clone元素,因此您可以在该元素内部执行所有角度优势.
| 归档时间: |
|
| 查看次数: |
7334 次 |
| 最近记录: |