Search code examples
javascriptangularjsdynamicangular-templatecache

angular bind scope data to templateCache


I have this function in my controller, which loads in a template

$http.get('scripts/routes/template.html', { cache : $templateCache})
    .then(function(val){
        var returnedTemplate = val.data; // returns string
        $scope.name = 'blah blah';
        $scope.message = 'Good day';
    });

The template that that it loaded in by val.data, is a string

<h3 class="md-title">{{name}}</h3>
<p class="md-title">{{message}}</p>

How do I get the string that is returned from the loaded template and bind the scope vars to the string?

The result I need is

<h3 class="md-title">blah blah</h3>
<p class="md-title">Good day</p>

I have tried to use the $compile functions to bind the data to the string but to no avail.

Thanks in advance for the help


Solution

  • you need to manually compile the html after the binding. create a directive like this.

    .directive('dynamic', function ($compile) {
      return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
          scope.$watch(attrs.dynamic, function(html) {
            ele.html(html);
            $compile(ele.contents())(scope);
          });
        }
      };
    });
    

    then call this in the html and bind the html string to directive

    <div dynamic="returnedTemplate"></div>
    

    Controller

    $scope.name = 'blah blah';
     $scope.message = 'Good day';
     $scope.returnedTemplate = '<h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p>'
    

    Demo

    angular.module("app",[])
    .controller("ctrl",function($scope){
    
            $scope.name = 'blah blah';
            $scope.message = 'Good day';
     $scope.returnedTemplate = '<h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p>'
    }).directive('dynamic', function ($compile) {
      return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
          scope.$watch(attrs.dynamic, function(html) {
            ele.html(html);
            $compile(ele.contents())(scope);
          });
        }
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="ctrl">
     <div dynamic="returnedTemplate"></div>
    </div>