I'm attempting to follow this SO answer explaining how to render a recursive JSON structure using a directive. However, unlike the answer provided, my data is not known when the DOM is loaded and Angular runs for the first time.
Instead, my data is retrieved from an HTML input field and stored in an Angular Service (when the user submits the form).
How can I keep an Angular Directive up-to-date when the Service's data is modified?
Update in response to answer
@musically_ut provided an excellent answer that has helped, but revealed a related problem, preventing an implementation (updated here).
The directive renders HTML that contains Angular {{expressions}}
which access data stored in $scope
. Since the original solution was to $watch
when the service had it's data ready. How can I ensure the 'new' data is added to $scope
before the directive renders?
An overview of the architecture and flow is:
ControllerA
-> Get input from userControllerA
-> Use service to transform dataControllerB
->$watch
for changes in serviceDirective
->$watch
for changes in serviceControllerB
-> Add data to$scope
Directive
-> Display transformed data (from service) using directives
The problem is between steps 5 and 6. The directive renders {{expressions}}
before ControllerB has added the data to $scope
. Even if this did work, it feels way too complex and 'hacky'.
In fact, to regress, I'm using $watch
in ControllerB to listen for when the transformed data is ready in a service. Even this feels a little overkill (the service makes no asynchronous calls).