2017-11-17 2 views
2

私は小さなテンプレートがたくさんあるので、それらを1つのhtmlファイルに入れます。angularJs:ng-include内のng-template

smallTemlates.html

<script type="text/ng-template" id="template1.html"> 
... 
</script> 
<script type="text/ng-template" id="template2.html"> 
... 
</script> 

それから私はindex.html内部smallTemlates.htmlが含まれます。

index.html

<body ng-app="myapp" id="my-app"> 
     <div ng-include="'pathTo/smallTemlates.html'"></div> 
</body> 

それから私は$ templateRequestを使用して、私のコントローラ/サービスの内部でこれらのテンプレートにアクセスしようとしましたが、それは404エラーを投げています。

$templateRequest(component.popoverTemplateUrl).then(function(html) { 
    var template = html // 404 error 
    }); 

しかし、私はそれだけで正常に動作を下回るようindex.htmlにdirecltyこれらのテンプレートを追加した場合。

<body ng-app="myapp" id="my-app"> 
<script type="text/ng-template" id="template1.html"> 
... 
</script> 
<script type="text/ng-template" id="template2.html"> 
... 
</script> 
</body> 
+0

'smallTemlates.html'のコンテンツが利用可能かどうかを確認しましたか? –

+0

@DhanaSekarはい利用可能です。 –

答えて

0

テンプレートのために別の要求を行う必要はありませんので、あなたは、代わりに$ templateRequest$ templateCacheを使用する必要があります。 ng-includeはデフォルトで既にこれを行います。あなたがテンプレートのコンテンツを取得するには、次のダイジェストを待つ必要が

var app = angular.module("myApp", []); 
app.controller("myCtrl", function($scope,$templateCache,$timeout) { 

    $timeout(function(){ 
    var template = $templateCache.get('smallTemlates.html').then(function(html){ 
     console.log("smallTemlates"); 
     console.log(html.data); 
     $timeout(function(){ 
      var template1 = $templateCache.get('template1.html'); 
      console.log("template1"); 
      console.log(template1); 
     }); 
    }); 

    }); 
}); 

HTML:

<!DOCTYPE html> 
<html> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> 
<link rel="stylesheet" href="style.css"> 
<script src="script.js"></script> 
<body> 

<div ng-app="myApp" ng-controller="myCtrl"> 

    <div ng-include="'smallTemlates.html'"></div> 
</div> 

</body> 

smallTemplates.html

<script type="text/ng-template" id="template1.html"> 
template1zzasdfasdf 
</script> 
<script type="text/ng-template" id="template2.html"> 
template2 
</script> 

Plunker Link here(結果を確認するコンソール)

+0

ありがとう@gaurav、$ timeoutがキーでした –

+0

@farhanlatheefがうれしかったです:-) –

関連する問題