I have been delving into JavaScript and AngularJS for approximately a month now, but I still find myself unsure of when to use directives.
For example: I am looking to display appointments in a table with the date as the table header. I envision having buttons on the left and right of the table to load appointments from the previous week and the next week, respectively.
My initial approach would involve creating a view model/controller to store data for the current week. I would then add two methods to the controller - loadPreviousWeek
and loadNextWeek
- that retrieve appointment data from an appointmentProvider
. In the view, I would utilize ng-click
directive on the buttons to invoke these controller functions.
However, after researching directives further, my alternative approach emerges: I decide to establish an AppointmentService
responsible for storing data for the current week and capable of loading data for both preceding and subsequent weeks. Subsequently, I create a directive named loadWeek
, which attaches the onClick
event to its corresponding element. This onClick function triggers the methods located within the AppointmentService
. In this scenario, my view accesses the AppointmentService
directly through the controller.
Which approach do you believe is more effective? Please guide me if my understanding is misguided. Additionally, I would appreciate some practical examples showcasing the usage of directives.
Best regards, Cristan