1

On my form I have an icon which represents whether my entity is locked (shown by a locked padlock) or unlocked (an open padlock). At the model level, this is represented by a boolean property (isLocked). The user can toggle the entity between locked and unlocked by clicking the icon. This also updates the icon tool-tip text. This calls a controller method that toggles the entity.isLocked property. It is like a fancy kind of checkbox.

I can implement this in one of (at least) two ways:

1) Create a custom angular directive that changes the class of the icon element to show the correct icon and also sets the tool-tip text. The icon will then be a single DOM element in my view, decorated with the custom directive.

2) Put both the locked and unlocked icon elements in the DOM and show/hide each one using the custom ng-show directive.

Option 1 involves writing custom code which feels like the wrong thing to do, whereas option 2 makes maximum use of the built in Angular features, but leaves the HTML more cluttered.

In general, should I prefer the custom directive method (option 1) or the HTML method (option 2) or some other method? Which would be considered more idiomatic for Angular do you think? And, more importantly, why?

I did consider putting this on StackOverflow, but it feels like it would be considered off-topic there because it is a matter of opinion in the end...

2 Answers 2

2

You can actually use angular builtins here AND only have a single DOM element!

<img ng-src="{{isLocked ? 'closed-padlock.png' : 'open-padlock.png'}}" 
    alt="{{isLocked ? 'locked-text' : 'open-text'}}">

This will conditionally change the image's src and alt properties based on whether or not isLocked is set. Admittedly the ternary expression is a touch messy but it's all presentation logic so I feel it belongs in the DOM like that.

1
  • 1
    The icon is applied by a class, not as an image, but it would work the same using ng-class instead of ng-src I guess. Dec 6, 2013 at 23:34
1

I like Option 1 better. I feel like when you are showing and hiding things by change classes thus through the CSS it is faster and easier to mange.

This also reduces the amount of elements on the DOM

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.