0

I have an array of JSON within my controller, and I want to generate through the use of an ng-repeat several times the use of a directive that I created. Every time it would take the data from the array to pass to the directive by calling a specific directive's function in the template. I am able to get perfectly my string but because the resulting template has to be some HTML code, Angular doesn't interpret it.

If I change

    template: '< div ng-bind="getTemplate(thiselem)">< /div>',

for

    template: '< div ng-bind-html="getTemplate(thiselem)">< /div>',

(I have added some spaces before "div" keywords to allow showing the html code as well)

I have on my project pieces of my HTML executed but everything using normally some data between the curly brackets are not interpreted (should return undefined or null). How can I do to give access to these data and/or make the directive's template generate the result correctly ?

I have done this plunker to show you my problem.

Thank you very much in advance.

2 Answers2

0

You can interpolate the string that you are using in your directive. Please note that I'm injecting into the the directive the variable $interpolate. Here's the official documentation from the Angular's site: AngularJS: API: $interpolate

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.elements = [
      {id: 1, name: 'bonjour'},
      {id: 2, name: 'bonsoir'}
    ];
  $scope.text = 'Hello world';
});

app.directive("frameelement", ['$interpolate', function($interpolate) {
  return {
        restrict: 'EA',
        scope: {
            thiselem: '='
        },
        template: '<div ng-bind="getTemplate(thiselem)"></div>',
        link: function(scope, element, attrs) {
            scope.getTemplate = function(thiselem) {
                return $interpolate('<h1>{{thiselem.id}} : {{thiselem.name}} tt</h1>')(scope);
            }
        }
    };
}]);
TlonXP
  • 3,325
  • 3
  • 26
  • 35
0

You're returning the result of the getTemplate() function considering everything as string, including the passed object. You just have to use its actual value:

link: function(scope, element, attrs) {
    scope.getTemplate = function(thiselem) {
        return '<h1>' + thiselem.id + ':' + thiselem.name + 'tt</h1>';
    }
}

Here's the plunker: http://plnkr.co/edit/N5ziwjSRDWDMEWAH9ODl?p=preview

Jodevan
  • 732
  • 1
  • 6
  • 20