2015-11-06 68 views
1

我想设置元素的CSS属性顶部基地的高度。要做到这一点我创建这样的指令:如何访问Angular指令中的元素?

directive('errormsgbox', function($timeout) { 
    return { 
     restrict: 'EA', 
     scope: false, 
     replace:true, 
     templateUrl: 'submitter/reports/errormsgbox.html', 
     link: function(scope,element) { 
      $timeout(function(){ 
        $timeout(function(){ 
         console.log(element[0].offsetHeight); 

       },2000); 
      },2000)  
     } 
    }; 
}) 

指令HTML:

<span ng-if='expenses.hasBlockers || expenses.hasWarnigs' style='border:1px solid gray' ng-show='policyViolation && showpencil' class='msgbox'> 
    <ul> 
     <li ng-repeat='policymsg in expenses.policyMsg'> 
      <span class='floatleft' ng-class="showPolicyClass(policymsg.type)">{{policymsg.type}} - </span><span style='width:285px;' class='floatleft'>{{policymsg.message}}</span> 
      <div class='clear'></div> 
     </li> 
    </ul> 
</span> 

主HTML:

<td class="text-center" style='position:relative'> 
    <errormsgbox></errormsgbox> 
</td>// it is in a table cell, the content of directive is from ng-repeat in this table 

我需要访问<span>。但是你可以看到,指令工作正常,它会显示正确的信息,但每次它都会记录元素高度undefined。任何想法如何访问此?在开发者控制台

angular.element($0).scope() 

回答

1

右键单击与您要访问并点击“检查元素”的指令,在页面上,然后输入。这使您可以访问角度范围内的所有数据。这将有助于调试角度正在使用的数据。但是,更直接的回答你的问题,我做了类似的地方,我在一个指令中设置CSS属性。它会变成你的代码是这样的:

return { 
    restrict: 'EA', 
    scope: false, 
    replace:true, 
    templateUrl: 'submitter/reports/errormsgbox.html', 
    link: function(scope,element,attr) { 
     element.css({ 
        width: '360px', 
        height: '640px', 
        position: 'absolute', 
        top: '0px', 
        left: '0px', 
        background: '#FFF' 
       }); 
    } 
}; 
+0

哇,感谢分享'$ 0'功能。 –

+0

很酷的功能,但这不一定回答 – scniro

+0

谢谢你们的问题,但如何解决我的问题.... – linyuanxie

1

对于E指令,如<my-dir></my-dir>默认display值将设置为inline。你可以在这里做一些事情,或者利用replace: true的块元素或者简单地设置一个样式规则,在这个例子中,my-dir { display: block }。你甚至可以在你的指令link函数中调用elem.css('display', 'block')

JSFiddle Example - 记简化演示


随身携带inline-block沿float规则将采取边距和填充考虑审查offsetHeight

+0

在你的例子中,是的,它的工作原理,但如果我循环数据到li ng-repeat在你的例如,它给了我0,我认为链接函数在数据循环之前运行,这就是为什么指令中没有内容。它返回0作为高度。 – linyuanxie

+0

啊好的,只需在'$ timeout'中包装即可。我没有把它包含在我的小提琴示例中 – scniro

+0

@linyuanxie在这里你去[JSFiddle ng-repeat](https://jsfiddle.net/5hjkgezn/) – scniro

相关问题