Sibiraj
Sibiraj

Reputation: 4756

Angular Directives - How to set attributes to innerHML

how to set attributes to the inner HTML

tpl.html

<div class="my-templeate"></div>

HTML

<template></template>

directive

app.directive('template', ['$compile', function($compile) {
        return {
            restrict: "EA",
            templateUrl: './tpl.html',
            link: function($scope, $elm, $attr) {

                var elm =$elm[0].innerHTML;

                elm.attr('id', "someId");
            }
        };
    }]);

Here I want to set attributes to the innerHtml <div class="my-templeate"></div> that is appended to the <template></template> element.

How can I do that?

Upvotes: 1

Views: 34

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21495

As long as you have this massive and powerful framework at your disposal, you may as well make some use of it. Set data on scope and let the template read it, instead of bypassing Angular to edit the DOM on your own. The template:

<div class="my-template" id="{{someId}}"></div>

The directive:

app.directive('template', ['$compile', function($compile) { // $compile is unnecessary here unless you're using it for something else in this directive
    return {
        templateUrl: './tpl.html',
        link: function($scope, $elm, $attr) {
            $scope.someId = "whatever";
        }
    };
}]);

In general, if you're manipulating the DOM directly when using Angular, you're probably doing things either the hard way or the completely wrong way.

Upvotes: 1

Related Questions