Javascript angularjs中的动态模板到指令
我需要根据日期决定模板。我看到了一个好消息。 但在那个例子中,模板非常简单,他可以使用字符串。在我的例子中,我想使用php生成模板,所以我这样使用它:Javascript angularjs中的动态模板到指令,javascript,angularjs,directive,Javascript,Angularjs,Directive,我需要根据日期决定模板。我看到了一个好消息。 但在那个例子中,模板非常简单,他可以使用字符串。在我的例子中,我想使用php生成模板,所以我这样使用它: eng.directive('vis', function ($compile) { var getTemplate = function(ir) { var k = (ir.visits.last && parseInt(ir.visits.last.done))?'V':'E'; var s = (ir.dat
eng.directive('vis', function ($compile) {
var getTemplate = function(ir) {
var k = (ir.visits.last && parseInt(ir.visits.last.done))?'V':'E';
var s = (ir.data.kind == 0)?'H':'V';
return s+k+'T';
}
var linker = function(scope, element, attrs) {
scope.$watch('ir',function(){
if (!scope.ir) return;
element.html(jQuery('#'+getTemplate(scope.ir)).html()).show();
$compile(element.contents())(scope);
})
}
return {
restrict: "E",
rep1ace: true,
link: linker
};});
模板包括:
<div id=HVT style="display:none">
<p>horizontal view template</p>
</div>
<div id=HET style="display:none">
<p>horizontal {{1+5}} Edit template</p>
</div>
<div id=VVT style="display:none">
<p>vertical view template</p>
</div>
<div id=VET style="display:none">
<p>vertical Edit template</p>
</div>
水平视图样板
水平{{1+5}}编辑模板
垂直视图模板
垂直编辑模板
我相信有一个更聪明的方法。
使用templateUrl更好吗?有人能告诉我如何在我的情况下使用它吗
编辑:有个问题。模板没有看到范围我找到了解决方案
在这个例子中
查找此代码:
app.directive("pageComponent", function($compile) {
var template_for = function(type) {
return type+"\\.html";
};
return {
restrict: "E",
// transclude: true,
scope: true,
compile: function(element, attrs) {
return function(scope, element, attrs) {
var tmpl = template_for(scope.component.type);
element.html($("#"+tmpl).html()).show();
$compile(element.contents())(scope);
};
}
};});
对于Angular,您不需要使用
id
s。另外,您可以使用ng show
,而不是display:none
:
<div ng-show="HVT">
<p>horizontal view template</p>
</div>
<div ng-show="HET">
<p>horizontal {{1+5}} Edit template</p>
</div>
...
。fiddle在控制器中有上述代码,因为我不知道您可能在哪里使用该指令。小提琴也只是硬编码“VET”,因为我不知道ir是什么样子。这也可以在AngularJS中创建动态模板: 在您的指令中,请使用:
template : '<div ng-include="getTemplateUrl()"></div>'
因为您可以访问范围参数,所以还可以执行以下操作:
$scope.getTemplateUrl = function() {
return '/template/angular/search/' + $scope.query;
};
因此,您的服务器可以为您创建一个动态模板。template&templateUrl可以使用如下函数:
function(el,attrs){return'/tmpls/'+attrs.template;}
我尝试了上述方法,现在即使我可以控制导航,它也可以正常工作,唯一的问题是我是否有动态状态(state('manualTest/:testName',)回到动态页面,ng init被调用了两次
$scope.getTemplateUrl = function() {
return '/template/angular/search';
};
$scope.getTemplateUrl = function() {
return '/template/angular/search/' + $scope.query;
};