27

ディレクティブのスコープに値を渡すことで、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.
        }
    });
4

7 に答える 7

54

可能ですが、ロードするテンプレートがスコープデータに依存している場合、ディレクティブの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));                
              });              
            } 
        }
    });

として使用されると仮定し<boom data='name'></boom>ます。ここで作業中のプランク:http://plnkr.co/edit/TunwvhPPS6MdiJxpNBg8?p = Preview

{{name}}テンプレートは最初に一度だけ決定する必要があるため、属性の評価を属性の解析に変更したことに注意してください。

于 2013-01-31T18:09:04.970 に答える
16

これはAngularバージョン1.1.4+の新機能です。現在の不安定版(1.1.5)を使用すると、ディレクティブのテンプレートURLに関数を渡すことができることがわかりました。関数の2番目のパラメーターは、以下に示すように、属性ディレクティブの値です。

公式の変更を示す未公開のドキュメントへのリンクは次のとおりです。

partials/template1.htmlからのテンプレートURLとして使用するには

HTML:

<div sub_view="template1"></div>

指令:

.directive('subView', [()->
  restrict: 'A'
  # this requires at least angular 1.1.4 (currently unstable)
  templateUrl: (notsurewhatthisis, attr)->
    "partials/#{attr.subView}.html"
])
于 2013-07-29T03:33:14.683 に答える
3

私も同様の問題を抱えていました

 return {
        restrict: 'AE',
        templateUrl: function(elm,attrs){return (attrs.scrolled='scrolled' ?'parts/scrolledNav.php':'parts/nav.php')},
        replace: true,

partnersSite.directive('navMenu', function () {
    return {
        restrict: 'AE',
        templateUrl: function(elm,attrs){return (attrs.scrolled='scrolled' ?'parts/scrolledNav.php':'parts/nav.php')},
        replace: true,
        link: function (scope, elm, attrs) {
            scope.hidden = true;
            //other logics
        }
    };
});
<nav-menu scrolled="scrolled"></nav-menu>

于 2015-07-23T11:11:02.943 に答える
2

pkozlowski.opensourceからの回答を少し変更しました。

から:

var boom = $parse(iAttrs.data)(scope);

に:

var boom = scope.data.myData

それは私のために働きました、そしてそれは使うことが可能です

<boom data="{{myData}}" /> 

ディレクティブで。

于 2013-10-23T09:28:39.513 に答える
2

この質問は、次のようにng-includeで修正されます。

MyApp.directive('boom', function() {
    return {
      restrict: 'E',
      transclude: true,
      scope: 'isolate',
      locals: { data: 'bind' },
      templateUrl: '<div ng-include="templateUrl"></div>',
      link: function (scope) {
        function switchTemplate(temp) {
          if (temp == 'x')
          { scope.templateUrl = 'XTemplate.html' }
          else if (temp == 'y')
          { scope.templateUrl = 'YTemplate.html' }
        }
      }
    }
});

ディレクティブのlink関数で任意のtempパラメータを使用してswitchTemplate関数を呼び出します。

于 2018-04-29T09:17:33.023 に答える
1

これは、以前の回答に関するいくつかの問題に対処するフォローアップ回答です。特に、テンプレートは1回だけコンパイルされます(これは、ページにテンプレートが多数ある場合に重要であり、リンクされた後のテンプレートへの変更を監視します。また、クラスとスタイルを元の要素からにコピーします。テンプレート(「replace:true」を使用する場合、angularが内部的に行う非常に洗練された方法ではありませんが、templateまたはtemplateUrlの関数を使用する現在のAngularでサポートされている方法とは異なり、スコープ情報を使用してロードするテンプレートを決定できます。

.directive('boom', ['$http', '$templateCache', '$compile', function ($http, $templateCache, $compile) {
    //create a cache of compiled templates so we only compile templates a single time.
    var cache= {};
    return {
        restrict: 'E',
        scope: {
            Template: '&template'
        },
        link: function (scope, element, attrs) {
            //since we are replacing the element, and we may need to do it again, we need
            //to keep a reference to the element that is currently in the DOM
            var currentElement = element;
            var attach = function (template) {
                if (cache[template]) {
                    //use a cloneAttachFn so that the link function will clone the compiled elment instead of reusing it
                    cache[template](scope, function (e) {
                        //copy class and style
                        e.attr('class', element.attr('class'));
                        e.attr('style', element.attr('style'));
                        //replace the element currently in the DOM
                        currentElement.replaceWith(e);
                        //set e as the element currently in the dom
                        currentElement = e;
                    });
                }
                else {
                    $http.get('/pathtotemplates/' + template + '.html', {
                        cache: $templateCache
                    }).success(function (content) {
                        cache[template] = $compile(content);
                        attach(template);
                    }).error(function (err) {
                        //this is something specific to my implementation that could be customized
                        if (template != 'default') {
                            attach('default');
                        }
                        //do some generic hard coded template
                    });
                }
            };

            scope.$watch("Template()", function (v, o) {
                if (v != o) {
                    attach(v);
                }
            });
            scope.$on('$destroy', function(){
                currentElement.remove();
            });
        }
    };
} ])
于 2014-12-30T21:41:12.653 に答える
0

それらの答えは良いですが、専門家ではありません。を使用する構文がありますがtemplateUrl、これはあまり使用しません。これは、URLを返す関数にすることができます。その関数にはいくつかの引数があります。もっと欲しいならここにクールな記事があります

http://www.w3docs.com/snippets/angularjs/dynamically-change-template-url-in-angularjs-directives.html

于 2015-07-22T16:04:31.270 に答える