1

I am looking for advice with regards to creating a generic controller which I can reuse in my application. As an example I have created the following GIST:

https://gist.github.com/heide-de/10832576 but here is the relevant code snippet:

angular.module('genericTestApp', [])
        .factory('Names', function() {
            return {
                names: []
            };
        })
        .controller('IndexController', function(Names) {
            Names.names = [
                {firstname:'Sarah', surname:'Schmitt'},
                {firstname:'Paul', surname:'Wells'},
                {firstname:'Felix', surname:'the cat'}
            ]
        })
        .controller('SecondIndexController', function(Names) {
            Names.names = [
                {firstname:'Octo', surname:'Cat'},
                {firstname:'Beth', surname:'Appleby'},
                {firstname:'Fred', surname:'Bloggs'}
            ]
        })
        .controller('TableController', function($scope, Names) {
            $scope.names = Names.names;
        })

What feels very wrong to me is that the TableController in this example relies on the fact that the injected Names factory needs to have been configured previously in the IndexController. The next developer that comes along will just inject Names, and will have no idea that it needs configuring prior to that.

Is there a better way of doing this with Angular?

Heidi_DE
  • 177
  • 3
  • 14
  • 1
    configuring the factory in the factory definition is no possibility? Anyway - tablecontroller still works even without configuration. You just have to check the length of names on the view. As fast as the factory is configured -the view will update accordingly. PS: specify your names as array not object! – Fuzzyma Apr 16 '14 at 08:14

1 Answers1

0

You're right in your approach – Configuring a factory in a controller is always a bad idea. A controller is supposed to contain view specific logic, and in my opinion should even only be included when that particular view is rendered. (that's how I write my apps anyway)

To configure anything when the application loads up, you need run, that should contain all the initial stuff that your app needs to do in the beginning.

This might be a good read.

Community
  • 1
  • 1
Ashesh
  • 2,978
  • 4
  • 27
  • 47