2014-05-04 34 views
3

我處於這種情況,我想將內聯樣式應用於基於我在控制器中定義的標誌的DOM元素。其原因是我無法更改視圖中使用的現有CSS,也無法擴展它。如何在Angular的ng-class中使用內聯樣式?

這就是說,這裏是我當前的視圖代碼:需要時

<label class="control-label" ng-class="{'margin-left:100px' : is_modal}">Hello</label> 

is_modal僅僅是我切換到真正的標誌/控制器錯誤。

上面的代碼不工作,我也試着:

<label class="control-label" ng-class="{'style=margin-left:100px' : is_modal}">Hello</label> 

但也不起作用。任何人都知道這是否可能?定義內聯樣式?

另一種選擇是NG-風格,但我似乎無法控制我的標誌is_modal綁定到NG-風格,因爲它不允許索要條件爲NG-類做...

感謝 亞歷

回答

6

如果你正在尋找一個內嵌的解決方案,然後這個特定的解決方案可能會爲你工作:

<label class="control-label" ng-style="is_modal && {'margin-left': '100px'}">Hello</label> 

,但如果你想有一組複雜的條件更加一致和維護的解決方案與您的風格追加話,我建議你創建一個你可能在你的ng-classng-style指令放置範圍功能。

例如

HTML

<label class="control-label" ng-style="getStyle(is_modal)">Hello</label> 

JAVASCRIPT

$scope.getStyle = function(is_modal) { 
    if(is_modal) { 
    return { 
     'margin-left': '100px' 
    } 
    } 
}; 

看到這個EXAMPLE

+0

很好的答案!這是我真正需要的,謝謝! – AlejandroVK

2

您可以使用ng-style指令:

<label class="control-label" ng-style="is_modal && {margin-left:'100px'}">Hello</label> 
+0

好的,給予好評呢!謝謝 – AlejandroVK

1

看到這個jsBin

創建一個函數來計算isModal並返回正確的風格,如:

$scope.isModel = true; // or whatever 

    $scope.labelStyle = function() { 
    if ($scope.isModel) { 
     return { 
     'margin-left': '100px' 
     } 
    } 
    } 

然後您的標記看起來像:

<label ng-style="labelStyle()">Hello</label> 
+0

這是一個很好的回答湯姆,謝謝你,但是因爲ryeballar答案更完整,他得到了正確的答案,我也會贊同你的意見,因爲也指出了正確的方向,謝謝! – AlejandroVK