0

I want to create a directive that takes an array of strings, and organizes them in a table, where there are 4 strings per row.

So for example, the array ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] would be rendered as:

a b c d
e f g h

For this, I can easily write a link function that manually manipulates the DOM (jQuery style) and renderes this table.

But this feels wrong since we already have directives such as ng-repeat that can do half of this work. I want to use the existing stuff that can help, and only code the new functionality.

How can I achieve this?

Aviv Cohn
  • 15,543
  • 25
  • 68
  • 131
  • Your question renders itself unanswerable. There is no "proper way" to accomplish every task to the exclusion of every other method; There are good ways to accomplish a task and bad ways to accomplish a task. In your particular case, an alternative good way to accomplish your task could be shown, but that doesn't make it the only correct way, or the way you should do every similar task. Therefore, what you should be asking for is the one thing you said you don't want anyone to answer. – Claies Nov 19 '15 at 23:34
  • There are two common ways this is handled, mostly depending on if you are using a responsive framework or not. http://stackoverflow.com/questions/27211799/angular-ng-repeat-add-bootstrap-row-every-3-or-4-cols has a few examples; One method is to use responsive resets and not try to control the DOM at all. The other method involves chunking the data into an array of arrays, and using two `ng-repeat` to iterate the outer array as rows and the inner array as columns. – Claies Nov 20 '15 at 02:30
  • you are correct though in your thought that manipulating the DOM isn't really the angular way. – Claies Nov 20 '15 at 02:36
  • @Claies Regarding the second option: will the `ng-repeat` go in the `template` field of the directive object, or into the actual template of the page? – Aviv Cohn Nov 20 '15 at 08:59
  • if you are writing a re-usable directive, you would put the repeats in the template. you could also not use a directive, and instead write a service that performs the data separation and keep the data in the controller, which would give you more flexibility in the output, particularly if you wanted the inner array to iterate over multiple data fields. – Claies Nov 20 '15 at 14:15

1 Answers1

0

Yes, you only have to specify template (through template or templateUrl), and use your variable inside.

Remember to map attribute to a scope variable, then you can use it without additional code.

Mateusz Sip
  • 1,280
  • 1
  • 11
  • 11