iLe*_*ing 26 angularjs angularjs-directive
是否可以通过在指令范围内传递值来动态更改templateUrl?我想将数据传递给控制器,控制器将根据从指令传递的数据呈现页面
可能看起来像这样的东西:
<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.
}
});
Run Code Online (Sandbox Code Playgroud)
pko*_*rce 53
这是可能的,但是当您要加载的模板依赖于某些范围数据时,您不能再使用该指令的templateUrl
属性,并且您将不得不使用较低级别的API,即$http
和$compile
.
大概你需要做的事情(只能在链接功能中使用)是使用$http
(不要忘记涉及$templateCache
!)检索模板的内容,然后"手动"编译模板的内容.
这可能听起来像是很多工作,但在实践中它是相当简单的.我建议看一下使用这种模式的ngInclude
指令源.
这是这样一个指令的框架:
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));
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
假设它将被用作<boom data='name'></boom>
.在这里工作:http ://plnkr.co/edit/TunwvhPPS6MdiJxpNBg8? p= preview
请注意,我已将属性评估从{{name}}
属性解析更改为属性解析,因为模板应该只在开始时确定一次.
Epi*_*ine 16
这是Angular版本1.1.4+中的一个新功能.我刚刚发现,如果我使用当前的unstable(1.1.5),你可以将一个函数传递给一个指令的模板url.函数的第二个参数是属性指令的值,如下所示.
以下是未发布文档的链接,显示官方更改.
要使用partials/template1.html
从模板网址
HTML:
<div sub_view="template1"></div>
Run Code Online (Sandbox Code Playgroud)
指示:
.directive('subView', [()->
restrict: 'A'
# this requires at least angular 1.1.4 (currently unstable)
templateUrl: (notsurewhatthisis, attr)->
"partials/#{attr.subView}.html"
])
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
28823 次 |
最近记录: |