Search code examples
angularjsangularjs-ng-include

Include template from file in AngularJS


Not sure if I got it wrong. I'm not able to include template from a file via script tag. Any idea?

Template:

<script type="text/ng-template" id="test1">inside</script>
<script type="text/ng-template" id="test2" src="templateFile.html"></script>

<div ng-controller="MyCtrl">
  Select:
  <a href ng:click="tpl='first.html'">internal</a>
     | <a href ng:click="tpl='test1'">script inside</a>
     | <a href ng:click="tpl='test2'">script external</a>

  <div style="border: 1px solid;min-height: 20px">
    <ng:include src="tpl"></ng:include>
  </div>
</div>

Controller:

var myApp = angular.module('myApp', []);
function MyCtrl($scope, $templateCache) {
    $templateCache.put('first.html', 'First template');
}

JSFiddle: http://jsfiddle.net/aG8Zy/32/


Solution

  • Actually all required information exists on stackoverflow

    I try to sum up:

    • ng-include is unable to read src in that way
    • reading of template from third part domain should use $sce and more over there are CORS restrictions.

    Please see 1 and 2

    Template:

    <script type="text/ng-template" id="test1" src="https://tools.ietf.org/html/rfc1918">inside</script>
    <script type="text/ng-template" id="test2" src="http://mhnystatic.s3.amazonaws.com/angulartest/list.html"></script>
    
    <div ng-controller="MyCtrl">
      Select:
    <a href ng:click="tpl='first.html'">internal</a>
         | <a href ng:click="openTemplate('test1')">ietf.org</a>
         | <a href ng:click="openTemplate('test2')">amazonaws</a>
        <div style="border: 1px solid;min-height: 20px"><ng:include src="tpl"></ng:include></div>
    </div>
    

    App:

    var myApp = angular.module('myApp', [])
    
    .config(function($sceDelegateProvider) {
        $sceDelegateProvider.resourceUrlWhitelist([
            // Allow same origin resource loads.
            'self',
            // Allow loading from outer templates domain.
            'https://tools.ietf.org/**',
            'http://mhnystatic.s3.amazonaws.com/**'
        ]);
    })
    
    .controller('MyCtrl', function($scope, $templateCache, $sce) {
        $templateCache.put('first.html', 'First template');
    
        $scope.openTemplate = function(id) {
            var src = document.querySelector('script[id="' + id + '"]').getAttribute('src');
            $scope.tpl = $sce.getTrustedResourceUrl(src);
        };
    });
    

    jsFiddle: http://jsfiddle.net/glebv/msfbr1xr/15/

    But as you see domain amazonaws.com can be used for loading resources but tools.ietf.org doesn't allow it. Both of them were added to WhiteList

    You should use an approaches which allows CORS.