This is kind of a 'best practices' question, but I still think there may be a correct answer.
I have a directive with six configurable options. Should I set up six different attributes on the directive (like below):
<my-directive
my-width="300"
my-height="300"
my-status="true"
my-foo="yes"
my-bar="no">
</my-directive>
or, should I pass a configuration object into a single attribute (like below):
<my-directive my-options="options"></my-directive>
Is this just preference or is there a generally preferred method? Any feedback is appreciated. Thanks :)
This is a mostly matter of preference. Since you can achieve the eventual outcome with both routes. I personally prefer to see individual attributes as suggested in your first example for the sake of working with verbose, expressive elements.
Just by looking at <my-directive my-width="300" my-height....>
in your first example, I can make an educated guess as to what this directive is used for and can easily piece together what is going on. Just seeing my-options="options"
, I would have no idea unless I dug through some code to understand the intention of this element.
As a single developer on a project, though, this may be a low-priority consideration - often chalked up as "well, whats the difference?", but as you introduce other members working on the same code base, having verbosity can alleviate struggles to understand your intentions, especially to developers who are not as familiar with AngularJS.
As far as technical benefits, say for example you wish to only apply a style rule to elements whose attributes include my-foo
. This becomes trivial with css selectors with the following
[my-foo="yes"] {
background-color: dodgerblue;
}
[my-foo="no"] {
background-color: tomato;
}
Another quick example - say you have jQuery in your project and wish to do something like
$("[my-bar='no']") // do whatever
Doing these tasks the other route has the potential to be tricky. Consider this real-word example: A UX designer wants to leverage these manipulations, but is say, not very savvy with AngularJS - these tasks become unnecessarily painful.
When you begin to consider aspects and examples such as these, having granular control on your elements becomes invaluable. To your original interest in asking this question, surely everyone can understand the desire for consolidating this into something succinct like my-options="options"
- but striving for shorter code is not always advantageous.
All considered, a combination of both is likely ideal depending on the perceived importance of the attribute you are working with. height
, width
, status
? - likely important and descriptive enough to standalone. A complex statistical object with many fields used in directive processing? - likely qualifies to remain an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With