简体   繁体   English

Angular指令中的element.html()问题

[英]Issue with element.html() in Angular directive

I am new to Angular. 我是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"]. 我有一个指令,在linkFunction中,我可以通过使用attribute [“ attribute-value”]将范围设置为某个值。 I was expecting element.html() to provide the inner html of the directive. 我期望element.html()提供指令的内部html。

    .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... 在groupbar.html中,我正在使用类似这样的代码...

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

I was expecting to see "Some Text" and "Web Server" as output. 我期望看到“某些文本”和“ Web服务器”作为输出。 I am getting only Web Server as output, and instead of "Some Text", I am getting the following as output... 我只获得Web服务器作为输出,而不是“某些文本”,而得到以下输出...

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

You need to include text and the other attributes in your scope definition like so 您需要像这样在范围定义中包括text和其他属性

scope { text : '=' } and also you might wanna add transclude option to true to try and get the text inside your directive. scope { text : '=' } ,并且您可能想将transclude选项添加为true来尝试在指令中获取文本。 I'm sure you'll be interested to look at this part of the documentation Directive to manipulate the DOM 我确定您会对阅读文档指令以操纵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. 您必须将指令的transclude属性设置为true并且必须在templatetemplateurl的HTML元素内包含ng-transclude属性,以使指令的innerHTML呈现。

Here is the working plunker based on your code, 这是根据您的代码工作的插件,

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

Hope this helps!!!! 希望这可以帮助!!!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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