-1

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/

Sebastian Barth
  • 4,079
  • 7
  • 40
  • 59

1 Answers1

1

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.

Community
  • 1
  • 1
Gleb Vinnikov
  • 458
  • 4
  • 13
  • I see my JSFiddle was missleading. I rather wanted to load local sources from the same domain which are fine in the aspect of CORS. Though your answer cleared things up. Especially with `getTrustedResource()`. Thx. – Sebastian Barth Nov 23 '14 at 10:05