2013-03-14 20 views
3

我试图通过AngularJS动态设置div的宽度。AngularJS - 将自定义类指令应用于ng-repeat项

<ul id="contents"> 
    <li ng-repeat="content in contents"> 
    <div class="content_right custom_width"> 
     <div class="title">{{content.title}}</div> 
    </div> 
    </li> 
</ul> 

与下面的指令

myApp.directive("custom_width", function() { 
    return { 
    restrict:"C", 
    link: function(scope, element, attrs) { 
     element.css("width", 400); 
    } 
    } 
}); 

但什么也没有发生。我尝试在“link:function ..”内设置“console.log”,但没有打印出来。我在这里错过了什么?

谢谢你的时间。

回答

4

指令定义使用驼峰:

myApp.directive("customWidth", function() { 
    return { 
    restrict:"C", 
    link: function(scope, element, attrs) { 
     element.css("width", 400); 
    } 
    } 
}); 

Directive docs

在AngularJS,骆驼情况下(lowerCamelCase)定义指令和访问属性(从指令内)时被使用,并且蛇情况下(dash-case - 无论你想调用它)用于引用HTML元素中的指令和/或属性。

+0

Doh!谢谢。傻我。 – ericbae 2013-03-14 11:40:40

+1

AFAIK'snake_case'带有下划线,通常用于数据库。 – Frizi 2013-07-16 13:08:15