As I work on a complex single page application in Angular, I find myself needing to manage two types of data. First, there is the Model data which pertains to information retrieved from and sent to the backend API server. Second, there is ViewState data which includes details related to UI elements that are specific to the application state.
I am contemplating the best approach to handle this situation. In some of my more intricate controllers, I have an ng-repeat loop for elements, each with expandable UI components. The instinct is to use ng-if to toggle the visibility of these elements by attaching a '.showing' variable to the object. For instance, something like
ng-repeat="user in users", ng-click="user.showing = !user.showing", ng-if="user.showing"
might be found in multiple divs. This method simplifies tracking the view state of repeated items as it's directly connected to the repeat.
However, this approach has its drawbacks - it may overwrite fields fetched from the API server. Additionally, since I cache data models for efficiency and real-time updates, the view state can persist even when navigating away and back or if the same data appears twice on the screen (e.g., displaying a user profile in multiple places).
To address this issue, I could separate view state variables within the controller but this would complicate ng-repeats (requiring $index lookup). Another option is creating a directive specifically for managing this problem, isolating scope and simplifying state tracking.
Currently, I am inclined towards using directives as it aligns with the Angular development methodology. Each UI element doesn't necessarily need to share its state externally; my current practice stems from starting with large HTML templates and adding ng-repeat directives. Breaking down components like Post, Comment, Author into directives allows them to maintain their own state independently.