2013-03-14 45 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