Rahul Soni
Rahul Soni

Reputation: 4968

Issue with element.html() in Angular directive

I am new to Angular. I have a directive and in the linkFunction I am able to set the scope to a certain value by using attributes["attribute-value"]. I was expecting element.html() to provide the inner html of the directive.

    .directive("sfGroupbar", function () {
    var linkFunction = function (scope, element, attributes) {
        scope.text = element.html();
        scope.attr = attributes["text"];
    };

    return {
        restrict: 'E',
        templateUrl: "controls/groupbar.html",
        link: linkFunction,
        scope: {}
    };

In my view, I am using the directive like so...

<sf-groupbar warning="50" error="80" text="Web Server">Some Text</sf-groupbar>

In groupbar.html, I am using the code like so...

<div ng-controller="groupbarController">
{{text}} <br />
{{attr}}
</div>

I was expecting to see "Some Text" and "Web Server" as output. I am getting only Web Server as output, and instead of "Some Text", I am getting the following as output...

<div ng-controller="groupbarController">
{{text}} <br />
{{attr}}
</div>

Upvotes: 0

Views: 58

Answers (2)

Alhuck
Alhuck

Reputation: 1029

You have to set transclude property of the directive to true and have to include ng-transclude attribute inside the template or templateurl 's HTML element to make innerHTML of the directive to render.

Here is the working plunker based on your code,

http://embed.plnkr.co/sXoLPxeFA21fxzzeAcVs/preview

Hope this helps!!!!

Upvotes: 1

Yazan Rawashdeh
Yazan Rawashdeh

Reputation: 1041

You need to include text and the other attributes in your scope definition like so

scope { text : '=' } and also you might wanna add transclude option to true to try and get the text inside your directive. I'm sure you'll be interested to look at this part of the documentation Directive to manipulate the DOM

Upvotes: 1

Related Questions