使用属性cant的angular指令获取元素内部html

时间:2016-07-04 10:12:04

标签: javascript angularjs angularjs-directive

我正在尝试使用属性而不是自定义指令中的元素。

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

我创建了“dotdot&#39;用于检查描述长度的指令。

代码如下:

  .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                          
        }
    }
})

我在控制台中没有得到任何东西(console.log(ele [0] .innerHTML)),因为我想要进一步操作文本内容的长度。

1 个答案:

答案 0 :(得分:0)

首先,您将指令限制为“E”(E代表元素)。这意味着只有<dotdot>{{ description }}</dotdot>才有效。您提供的HTML会将dotdot显示为属性。因此restrict: 'E'应为resrict: 'A'(A代表属性)。

其次,为什么不通过它的范围将描述的值传递给指令?类似<div dotdot="description"></div>的内容。 $watch更改会更容易,并采取相应的行动。另外,如果您将代码保存在这样的链接函数中,则可能会更改您的console.log将输出{{description}},因为摘要周期尚未运行。 (这不是你想要的)。

相关问题