Jeffarese Jeffarese - 4 months ago 15
AngularJS Question

Should I pass data between directive and service?

I have a page with a controller that has a directive that displays a form with inputs.

The directive has an object that contains all the inputs (and their ng-model) that are displayed on the form. This binds the form inputs data to the object variable inside the directive.

I need to display results (and other actions) submiting the data of the form.

For that I created a service that handles the business logic and thae ajax calls.

The questions here is... how should I access the form data from the service to perform the required actions? I thought about accessing the directive variable from the service, but I'm not sure how to do it and if this is the right way in the first place.

Answer

The service should hold a model which is basically the javascript object of your form.

The directive should inject the service and add that object on his scope(a reference).

The directive's template should speak with the directive's scope and display the form.

Changing a value on the view will reflect the service since we they have the same reference and the view will update the directives scope since there is two way binding.