4

日付に基づいてテンプレートを決定する必要があります。良い例を見ました。しかし、その例では、テンプレートが非常に単純であるため、文字列を使用できました。私の場合、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 を使用する方が良いですか? 誰かが私の場合にそれを使用する方法を教えてもらえますか?

編集:問題があります。テンプレートはスコープを認識しません

4

3 に答える 3

3

ここで解決策を見つけます

この例では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);
            };
        }
    };});
于 2013-03-14T15:16:44.087 に答える
2

Angular では、s を使用する必要はありません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>
...

$watch コールバック (コントローラーまたはディレクティブで定義できます) は、適切なスコープ プロパティを変更するだけです。

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

フィドル。ディレクティブを使用している場所がわからないため、フィドルにはコントローラーに上記のコードがあります。irまた、フィドルは「VET」をハードコードするだけです。これは、どのように見えるかわからないためです。

于 2013-03-14T18:16:47.177 に答える