Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have angularjs template as a string including "ng-repeat" and other directives. I want to compile it in the controller to produce the result HTML as string.

Example on what I want to apply in Angular:

Input:
-------
var template = '<div ng-repeat="item in items">{{item.data}}</div>';

Output:
--------
var result = '<div>1</div><div>2</div><div>3</div><div>4</div>';

I want this to be done in the controller I've and I tried the following:

var template = '<div ng-repeat="item in items">{{item.data}}</div>';
var linkFunction = $compile(template);
var result = linkFunction($scope);

console.log(result); // prints the template itself!

Thanks!

share|improve this question
up vote 5 down vote accepted

Give this a whirl:

var template = angular.element('<div ng-repeat="item in items">{{item.data}}</div>');
var linkFunction = $compile(template);
var result = linkFunction($scope);
$scope.$apply();

console.log(template.html());
share|improve this answer
    
It throws "Error: $apply already in progress". I'm using Angular 1.0.8 – phikry Oct 15 '14 at 16:13
    
Try changing "$scope.$digest();" to "$scope.$apply();" - see my edit. – Fordio Oct 16 '14 at 7:17
    
In my application it throws: $rootScope:inprog "Action Already In Progress": $digest already in progress (using ng 1.5.5) – big_p May 30 at 10:03

For this purpose I made myself a directive couple of projects ago:

angular.module('myApp')

.directive('ngHtmlCompile', ["$compile", function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngHtmlCompile, function (newValue, oldValue) {
                element.html(newValue);
                $compile(element.contents())(scope);
            });
        }
    }
}]);

and then for example:

<div ng-html-compile='<div ng-repeat="item in items">{{item.data}}</div>'></div>

or even the string can be dynamic:

<div ng-repeat="item in items" ng-html-compile="item.template">
</div>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.