Paul Taylor
Paul Taylor

Reputation: 5751

Binding a template to data in AngularJS

I want to bind content from an template to data in an Angular application. The template is stored in an html file and contains binding expressions:

<div>
    <div class="case-header">
        <h3>Case Details</h3>
    </div>
    <div class="case-body">
        <div>
            <label>Case Number:</label><div>{{item.CaseNumber}}</div>
        </div>
        <div>
            <label>Name:</label><div>{{item.CandidateName}}</div>
        </div>
        ...
    </div>
</div>

The element providing the context and data for the template is a row in an ng-grid. In the function below, I create a new scope to contain the data for the current row. The contents of a template is retrieved from an html file and cached to a property when the controller is constructed. However, the $compile call does not bind the data as I want. The function returns the template markup with the binding expressions still in it. I have tried both styles of binding expression.

    $scope.getTooltip = function (row) {
        var scope = $scope.$new();
        scope.item = row.entity;
        var elem = angular.element($scope.template);
        var result = $compile(elem)(scope);
        return result.html();
    };

The call to $compile appears to be correct vis the documentation, but I guess I must have misunderstood something.

How do I get the data values injected into the template?

Plunker

Here's a Plunker to play with.

Upvotes: 1

Views: 2171

Answers (1)

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

The $compile(scope) returns a reference to original dom element or clone of it so you should append it to some element . I have updated your plunker http://plnkr.co/edit/qatH4XNKPxjPyicur67T?p=preview so see it working.

Upvotes: 1

Related Questions