AngularJS ng-include

HTML

<div ng-controller="Ctrl">
    <select ng-model="template" ng-options="t.name for t in templates">
        <option value="">(blank)</option>
    </select>url of the template: <tt>{{template.url}}</tt>

    <hr/>
    <div cache-include src="template.url" onload='myFunction()'></div>
</div>
<!-- template1.html -->
<script type="text/ng-template" id="template1.html">
    <div ng-controller="SubCtrl">
      <div>Content of template1.html</div>
      <div>{{count}}<button ng-click="inc()">+</button></div>
    </div>
</script>
<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
    <p ng-class="color">Content of template2.html</p>
</script>

CSS

.red {
    color:red;
}

JavaScript

function Ctrl($scope) {
    $scope.templates = [{
        name: 'template1.html',
        url: 'template1.html'
    }, {
        name: 'template2.html',
        url: 'template2.html'
    }];
    $scope.template = $scope.templates[0];

    $scope.myFunction = function () {
        $scope.color = 'red';
    }
}

function SubCtrl($scope) {
    if(typeof $scope.count === 'undefined'){
        $scope.count = 0;
    }
    $scope.inc = function () {
        $scope.count += 1;
    }
}

angular.module('app', [])
    .directive('cacheInclude', function ($compile, $http, $templateCache) {
    return {
        link: function (scope, element, attrs, ctrl) {
            var cache = {};
            var currentElement = element;
            var replaceCurrent = function(cacheEntry) {
              
                currentElement.replaceWith(cacheEntry);
                currentElement = cacheEntry;
            };
            
            scope.$watch(function(){
                return scope.$eval(attrs.src);
            }, function () {
                var src = scope.$eval(attrs.src);
               
                if (!cache[src]) {
                    $http.get(src, {cache: $templateCache}).then(function (result) {
                        
                        cache[src] = $compile(result.data.trim())(scope.$new());
                        replaceCurrent(cache[src]);
                    });
                } else {
                    
                    replaceCurrent(cache[src]);
                }
            });
        }
    }
});