简体   繁体   中英

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>

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

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!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM