Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 218
sajjad Avatar asked Mar 11 '14 10:03

sajjad


People also ask

Can we use two ngStyle in angular?

The value of the expression is normally a string. With style binding we can set only a single style, however to set multiple styles we can use ngStyle directive.

Can we use NgClass and ngStyle together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

What is the difference between NgClass and ngStyle?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.

What is the difference between style and ngStyle?

ngStyle is an Angular directive that gives you the flexibility to do this, where as style is a regular HTML property to which you can only bind values one by one. That's the difference between the two of them.


1 Answers

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)}}">
like image 117
caffeinated.tech Avatar answered Oct 08 '22 10:10

caffeinated.tech