2013-03-14 91 views
4

我需要根据日期来决定模板。我看到一个很好的example。 但在这个例子中,模板非常简单,他可以使用字符串。在我来说,我想用PHP来制作模板,所以我用这种方式:动态模板指向angularjs

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> 

我肯定有一个更聪明的方法。 使用templateUrl更好吗?有人可以告诉我如何使用它在我的情况?

编辑:有一个问题。模板不看范围

回答

16

这也有可能在AngularJS创建动态模板: 在你的指令使用:因为你有机会获得

$scope.getTemplateUrl = function() { 
    return '/template/angular/search'; 
}; 

template : '<div ng-include="getTemplateUrl()"></div>' 

现在您的控制器可以决定使用哪个模板您的范围参数,您也可以这样做:

$scope.getTemplateUrl = function() { 
    return '/template/angular/search/' + $scope.query; 
}; 

所以你的服务器可以为你创建一个动态模板。

+9

template&templateUrl可以采用如下函数:'function(el,attrs){return'/ tmpls /'+ attrs.template; }' – 2013-11-22 20:32:19

+0

我试过上面的方法,现在它对我的工作很好,即使我有导航的控制权,唯一的问题是如果我有动态状态(状态('manualTest /:testName'),并且回到动态状态页面,ng -init被调用两次 – Anand 2017-11-06 07:41:52

3

,我觉得在这个例子中http://jsbin.com/ebuhuv/7/edit

解决here

找到这段代码:

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); 
      }; 
     } 
    };}); 
2

具有角,你并不需要使用id秒。此外,而不是display:none可以使用ng-show

<div ng-show="HVT"> 
    <p>horizontal view template</p> 
</div> 
<div ng-show="HET"> 
    <p>horizontal {{1+5}} Edit template</p> 
</div> 
... 

你$表回调(你可以在控制器或在指令定义),然后只需修改相应的作用域属性:

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'; 
} 
$scope.$watch('ir', function() { 
    if (!$scope.ir) return; 
    // hide all, then show the one we want 
    $scope.HVT = false; 
    $scope.HET = false; 
    $scope.VVT = false; 
    $scope.VET = false; 
    $scope[getTemplate($scope.ir)] = true; 
}) 

Fiddle。小提琴在控制器中有上面的代码,因为我不知道你可能在哪里使用指令。小提琴也只是硬编码“VET”,因为我不知道ir是什么样的。