angularjs - Function or filter vs computed attribute with css class name -


i have user object , have complex logic, want unit test, takes user object , decides how should displayed - css class should used.

there 2 approach consider:

<td class="{{ user | classify }}"> 

or

<td class="{{ user.cssclass }}"><!-- or --><td ng-class="user.cssclass"> 

or

<td ng-class="computecssclass(user)"> 

the first approach assumes create filter based on provided user objects returns css class.

the second approach assumes add new attribute cssclass model , whenever new user object created (fetched rest api) compute cssclass attribute.

the third approach assumes create function computes css class provided user object.

what pros , cons of above 3 approaches?


i have created jsfiddle play these 3 approaches.

the significant difference can think of around data-binding

1st approach, using filter

<td class="{{ user | classify }}"> 

pro: leverage angular's powerful filter mechanism, shorter , nicer syntax

con: $watch put on user object watch changes, , call filter, loop through $filterprovider find correct provider function , execute (i guess you'll figure out overhead implication of process)

2nd approach, using object's property

<td class="{{ user.cssclass }}"><!-- or --><td ng-class="user.cssclass"> 

pro: normal 2-way binding (the magic of angular js), , doing in angular-way

con: not "con", approach leverage automatic 2-way binding, $watch on user object's property watch changes, , update class attribute

3rd approach

<td ng-class="computecssclass(user)"> 

pro: have more control of when class attribute got updated (by return value of function)

con: it's easier mess things up. [edited] overhead of $watch function: function executed multiple times in $digest , return value got comparing watch changes, can expensive.

if performance care most, 3rd approach choice you.

if want use ng-class, of above approaches, 2nd approach have least overhead.

you can consider one-time binding, or custom directive handle updating class attributes. if use "class" attribute, able leverage one-time binding syntax:

<td class="{{ ::user.cssclass }}"> 

pre-compiling presentation attributes data good, unless have specific requirement such changing user's dashboard background colour/image basing on current weather of his/her location (well, requirement, weather should $watch for)

i saw compute class on <td>. it's easy reach number of $watch slows page down table (read 2nd answer of referenced question above)

anyway, it's approach should use, basing on real-world context of application developing.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -