Search code examples
angularjsarchitecturerequirejsangularjs-serviceangularjs-controller

Angular.js sanity check: Services vs. Factories vs. Controllers... + Directives + Behavior


This article about when to use directives, services and controllers, as awesome and helpful as it is... has me massively confused about everything I think I know about the ideal structure of an angular application and I just need a sanity check:

If you have two inputs:

<label><span>false</span>
   <input type='radio' value='false' ng-value='false' ng-model='thing.exists' />
</label>
<label><span>true</span>
    <input type='radio' value='true' ng-value='true' ng-model='thing.exists' />
</label>

that are part of a larger form, which will in turn submit to pull in another form... and that information will later be shown for review, is this the correct way to architect that:

TLDR: Flow of execution:

ng-model="thing.exist" ==> thing ==> ThingController  ==> a service  ==> ...details... ==> getDetails?

Right now I have:

<div ng-controller='ThingController as thing'>
  <fieldset>
    <label><span>Doesn't exist</span>
     <input type='radio' value='false' name='checkExist'
            ng-value='false' ng-model='thing.exists' />
    </label>
    <label><span>Does exist</span>

      <input type='radio' value='true' name='checkExist'
           ng-value='true'   ng-model='thing.exists' />
    </label>

  </fieldset>
 <!-- ... -->
</div>

When the input changes,
I should use ng-change on the inputs to trigger the behavior (like the addition of a directive)... right (via a controller)?

I should use then controller to add the result of the ng-change to a service? Like... passing the model value (thing.exists) to a service so I can use that value later? As a complication factor- this application uses Require.js to manage dependencies.

(Actually, the article itself isn't the source of my confusion- it's the comments on the article that are killing me.)


Solution

  • That's pretty much it, you've got it right. The idea is the following:

    • Use directives for managing user interface interactions and -some- state changes
    • Use controllers for managing a shallow set of logic
    • Use services for sharing data, functionality and business logic.

    Aka, just like on your server - try not to load too much into a controller.