简体   繁体   English

使用属性的角度指令无法获取元素内部html

[英]angular directive using attribute cant get element inner html

I am trying something with attribute instead of element in custom directive. 我正在尝试使用属性而不是自定义指令中的元素的东西。

  <div dotdot>{{description}}</div>

I have created 'dotdot' directive to check length of description. 我创建了'dotdot'指令来检查描述的长度。

the code is below: 代码如下:

  .directive('dotdot', function(){
    return {
        restrict: 'A',
        transclude: true,
        replace: true,
        scope:true,
        link:function(scope,ele,attr){
            console.log(ele[0].innerHTML);// shows blank
            console.log(ele.html());     // shows blank                          
        }
    }
})

I am getting nothing in console (console.log(ele[0].innerHTML)) as I want length of text content for further operation. 我在控制台(console.log(ele [0] .innerHTML))中什么也没有得到,因为我想要文本内容的长度以便进一步操作。

First of all, you restrict your directive to 'E' (E stands for Element). 首先,将指令限制为“ E”(E代表Element)。 Which means only <dotdot>{{ description }}</dotdot> would work. 这意味着只有<dotdot>{{ description }}</dotdot>可以工作。 Your provided HTML displays dotdot as an attribute. 您提供的HTML显示dotdot作为属性。 So restrict: 'E' should be resrict: 'A' (A stands for Attribute). 因此, restrict: 'E'应为resrict: 'A' (A代表Attribute)。

Secondly, why don't you pass the value of description to the directive through it's scope? 其次,为什么不通过描述的范围将描述的值传递给指令呢? Something along the lines of <div dotdot="description"></div> . <div dotdot="description"></div>东西。 It would be easier to $watch changes and act accordingly. $watch更改并采取相应措施会更容易。 Plus, if you keep your code in the link function like this, there may be a change your console.log will output {{description}} , because the digest cycle has not run yet. 另外,如果您将代码保留在这样的链接函数中,则您的console.log可能会发生更改,将输出{{description}} ,因为摘要循环尚未运行。 (which is not what you want). (这不是您想要的)。

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

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