forrestmid
forrestmid

Reputation: 1504

Treat String as Template in AngularJS

How can one utilize a string contained within a variable as a template?

For example:

Controller

$scope.items = [
    {
         name: "Bruce Wayne"
    },
    {
         name: "Lucius Fox"
    }
];
$scope.template = "<input ng-model='item.name' type='text'>";

View

<div ng-repeat="item in items">
    <div ng-bind-html="<!-- The `template` variable defined in the controller. -->">
    </div>
</div>

I've tried $sce.trustAsHtml, which only doesn't connect with the actual scope when using things like ng-model='item.name'. Reading through the $sce docs I don't think that it provides anything that can trust a string as a template.

A fiddle for you to play with.

Upvotes: 1

Views: 79

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41377

to actually bind data from ng repeat to input need to compile the html. for that this directive can be used

app.directive('dynamic', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                element[0].innerHTML = html;
                $compile(element.contents())(scope);
            });
        }
    };
});

<div ng-repeat="item in items">
   <div dynamic="template">
   </div>
</div>

$scope.items = [
    {
         name: "Bruce Wayne"
    },
    {
         name: "Lucius Fox"
    }
];
$scope.template = "<input ng-bind='item.name' type='text'>"; 

Demo

Upvotes: 2

Related Questions