1

ディレクティブのリンク関数内にテンプレート URL を含めるにはどうすればよいですか? 私はこのようなことをしようとしています:

app.directive('something', function($compile,$timeout) {

   return: {

      link: function(scope,element,attrs) {

           var htmlText = ???? // HOW TO INCLUDE A TEMPLATE URL HERE??

            $compile(htmlText)(scope, function(_element,_scope) {
         element.replaceWith(_element);                 
    });

      }, 

   }

}); 

検索したところ、Angularディレクティブで使用できることがわかりましたtemplateUrllinkしかし、最終的にコンパイルされる内部に配置された変数にhtmlコードを保存しようとしています。通常、小さなコードの場合は、HTML を にインラインで入力するだけvar htmlTextです。しかし、コードがたくさんある場合は、それを別の html ファイルに保存してから、その変数に対してそれを呼び出します (上記の例のように)。だから私の質問は

1) 変数内のテンプレート URL へのリンクを追加するにはどうすればよいlinkですか?

2) URL パスを追加する場合、index.html ファイルが置かれている場所からの相対パスを追加しますか、それともディレクティブ ファイルが置かれている場所からのパスを追加しますか?

4

2 に答える 2

2

まあ、回避策として、でレンダリングするng-include法線で使用するだけでよいので、次のようになります。<div>$compile

link: function(scope,element,attrs) {

       var htmlText = '<div ng-include="path/to/template.html"></div>';

       $compile(htmlText)(scope, function(_element,_scope) {
       element.replaceWith(_element);                 
});

[編集]

このスレッドにはさらに優れた解決策があります。 パスは、Web サーバーの構成方法によって異なります。ただし、通常は、Index.html の相対パスです。

于 2014-03-29T08:15:03.577 に答える
1

$templateCacheを使用できます。

これがどのように機能するかを示すコードです:

<body ng-app="App">
    <!-- Include template in $templateCache AUTOMATICALLY -->
    <script type="text/ng-template" id="auto.tpl.html">
        <span style="background-color:yellow">{{title}}</span>        
    </script>

    <dir tpl-id="auto.tpl.html" title="Automatic"></dir>
    <dir tpl-id="manual.tpl.html" title="Manual"></dir>
</body>

脚本:

angular.module('App',[])
.directive('dir',['$templateCache','$compile',function($templateCache,$compile){
    return {
        restrict:'E',
        scope:true,
        link:function($scope, iElement, attrs){
            //Include template in $templateCache MANUALLY
            $templateCache.put('manual.tpl.html','<span style="background-color:red">{{title}}</span>');
            //----------------------------            

            $scope.title = attrs['title'];
            $compile($templateCache.get(attrs['tplId']))($scope,function(cElement){
                iElement.replaceWith(cElement);                
            });
        }
    };
}]);
于 2014-03-29T08:44:51.930 に答える