欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

不同的 动态 多个 css ng-style 有大用

How to get multi css rule for ng-style by function?

13

I need for apply multi css rule to html tag in angular form template.

<div class="form-control" id="data.objectStyle"  
  ng-model="data.type" 
  ng-style="getStyle(data.objectStyle)">
{{data.objectStyle.title}}
</div>

getStyle function in controller :

$scope.getStyle = function (taskType) {
    return {
         background-color:taskType.backColor,
         color: taskType.color,
         font-size:taskType.fontSize,
         font-family:taskType.font
    }
)};

taskType object:

{
    backColor:'#006',
    color:'#56DA',
    fontSize:12,
    font:'New Times Roman'
}

The getStyle function does not return a style! What to do?

11

EDIT

The docs specify that you need to wrap your keys in quotation marks so they aren't invalid JSON object keys:

return {
     "background-color": taskType.backColor,
     "color": taskType.color,
     "font-size":taskType.fontSize,
     "font-family":taskType.font
}

Old Answer (not using ng-style)  正确答案

While I never used ng-style, it doesn't seem to take objects. Rather it is an equivalent of ng-class but for single styles.

Try changing your function to:

$scope.getStyle = function (taskType) {

        return {
         "background-color:"+taskType.backColor+
         ";color:"+ taskType.color+
         ";font-size:"+taskType.fontSize+
         ";font-family:"+taskType.font+";";
    }
)};

and the html to use the regular style tag with a bind:

<div class="form-control" id="data.objectStyle"  
ng-model="data.type" style="{{getStyle(data.objectStyle)}}">



来自   https://stackoverflow.com/questions/22322567/how-to-get-multi-css-rule-for-ng-style-by-function









普通分类: