您可以即时更改 templateUrl 吗? [英] Can you change templateUrl on the fly?
问题描述
是否可以通过在指令范围内传递值来动态更改 templateUrl?我想将数据传递给控制器,该控制器将根据从指令传递的数据呈现页面
可能看起来像这样:
<boom data="{{myData}}"/>.directive('boom', 函数 {返回 {限制:'E',转置:真实,范围:'隔离',当地人:{数据:'绑定'},templateUrl: "myTemplate({{boom}}})"//<- 这当然行不通.}});
这是可能的,但是当你的模板被加载依赖于一些范围数据时,你不能使用指令的 templateUrl
属性不再,您将不得不使用较低级别的 API,即 $http
和 $compile
.
大致上您需要做的(仅在链接函数中可能)是使用 $http
检索模板的内容(不要忘记涉及 $templateCache
!)然后手动"编译模板的内容.
听起来可能需要大量工作,但实际上它相当简单.我建议看看 ngInclude
指令 sources 使用此模式的地方.
这是这样一个指令的骨架:
app.directive('boom', function($http, $templateCache, $compile, $parse) {返回 {限制:'E',链接:函数(范围,iElement,iAttrs){var 繁荣 = $parse(iAttrs.data)(scope);$http.get('myTemplate'+boom, {cache: $templateCache}).success(function(tplContent){iElement.replaceWith($compile(tplContent)(scope));});}}});
假设它将用作
.在这里工作:http://plnkr.co/edit/TunwvhPPS6MdiJxpNBg8?p=preview
请注意,我已将属性评估从 {{name}}
更改为属性解析,因为模板可能只应在开始时确定一次.
Is it possible to change templateUrl on the fly by passing values in the directive's scope? I want to pass data to controller that will render the page based on the data that passed from the directive
something maybe that looks like that:
<div>
<boom data="{{myData}}" />
</div>
.directive('boom', function {
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { data: 'bind' },
templateUrl: "myTemplate({{boom}}})" // <- that of course won't work.
}
});
It is possible, but when your template to be loaded depends on some scope-data you can't use the directive's templateUrl
property anymore and you will be obliged to use lower-level API, namely $http
and $compile
.
Roughly what you need to do (only possible in the linking function) is to retrieve template's content using $http
(don't forget to involve $templateCache
!) and then compile template's content "manually".
It might sound like it is a lot of work but in practice it is rather straightforward. I would suggest having a look at the ngInclude
directive sources where this pattern is used.
Here is a skeleton of such a directive:
app.directive('boom', function($http, $templateCache, $compile, $parse) {
return {
restrict: 'E',
link: function(scope , iElement, iAttrs) {
var boom = $parse(iAttrs.data)(scope);
$http.get('myTemplate'+boom, {cache: $templateCache}).success(function(tplContent){
iElement.replaceWith($compile(tplContent)(scope));
});
}
}
});
assuming that it would be used as <boom data='name'></boom>
. Working plunk here: http://plnkr.co/edit/TunwvhPPS6MdiJxpNBg8?p=preview
Please note that I've changed attributes evaluation from {{name}}
to attributes parsing since probably a template should be determined only once, at the beginning.
这篇关于您可以即时更改 templateUrl 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!