Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-style or style attribute with binding? Which is better? Which is faster? What is the difference?

Tags:

angularjs

I am optimizing my large application. I am confused between following two approach, please help to decide which one is faster.

Inline style attributes

<div style="background-color:{{item.color}}"></div> 

Using ng-style

<div ng-style="{'background-color':item.color}"></div> 

Using once-style

<div once-style="{'background-color':item.color}"></div> 

Note : For once-style, I have used AngularOnce Directive.

Thanks in advance. Please tell me which one is faster and why.

like image 716
Jay Shukla Avatar asked Mar 14 '14 10:03

Jay Shukla


People also ask

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.

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.

Why we use ngStyle in Angular?

The ngStyle attribute is used to change or style the multiple properties of Angular. You can change the value, color, and size etc.


2 Answers

One time bind is available after Angular 1.3.

You can do this way without depending on third-party libraries:

<div ng-style="::{'background-color': item.color}"></div> 

I didn't measure the performance, but I'm pretty sure that its better than without the colons.

like image 77
leocborges Avatar answered Sep 19 '22 22:09

leocborges


Since you are optimizing your considerably large application, performance is definitely under question and I think ngStyle performs better as it sets up watch on the model and will update the view only if the model has changed.

So I would go with ngStyle or onceStyle depending on your scenario:

<div once-style="{'background-color':item.color}"></div> 

Using {{}} will make Angular update the binding every digest cycle, even if the value has not changed.

like image 35
AlwaysALearner Avatar answered Sep 21 '22 22:09

AlwaysALearner