簡體   English   中英

angularjs中的動態模板指令

[英]dynamic template to directive in angularjs

我需要根據日期決定模板。 我看到了一個很好的例子 但在該示例中,模板非常簡單,以至於他可以使用字符串。 在我的情況下,我想使用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.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? 有人可以告訴我如何在我的情況下使用它嗎?

編輯:有問題。 模板沒有看到范圍

這也可以在AngularJS中創建動態模板:在您的指令中使用:

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

現在您的控制器可以決定使用哪個模板:

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

因為您可以訪問范圍參數,所以您還可以:

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

因此,您的服務器可以為您創建動態模板。

我在這里找到解決方案

在這個例子http://jsbin.com/ebuhuv/7/edit

找到這段代碼:

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 另外,您可以使用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>
...

您的$ watch回調(您可以在控制器或指令中定義)可以簡單地修改相應的scope屬性:

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

小提琴 小提琴在控制器中有上面的代碼,因為我不知道你可能在哪里使用該指令。 小提琴也只是硬編碼“VET”,因為我不知道什么ir樣子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM