1

Currently I have a bunch of controllers that seems a little too bulky for my liking in that they manage both the logic and the storing of data.

For instance let us take a over simplified register controller:

$scope.username = "";
$scope.password = "";

$scope.validateUsername= function(){
  ......
}
$scope.validatePassword= function(){
  ......
}

$scope.updateUserConfig = function(){
     //a rest call here
}

ok so to me this seems like it is wrong because the controller is storing data, performing logic and making calls to a rest service.

I thought the controller should be the logic for the view it is used for while the "model" i.e. username and password should be somewhere else as well as the call to the rest service.

I have looked about and have seen people employing factories that are injected into the controller for the rest calls; as these factories will not store state they can be shared across the entire application, so this seems like a good idea ?

I am unsure about the data aspect though, is it normal for data to be stored within the controller or is there a better practice for this?

user1383163
  • 577
  • 1
  • 7
  • 24

1 Answers1

0

It is important to remember that your view must bind to the data/methods in the controller, so it must be exposed in such a way for this to be possible. In other words, there's nothing wrong with having these properties in your controller.

That being said, this data often comes from an external source or is needed in multiple views/controllers so it's common for a factory/service to return an object to a controller and then assign that object to a $scope property. This way you can abstract that layer away and share the data across your application without repeating yourself.

aw04
  • 10,857
  • 10
  • 56
  • 89
  • this is exactly what i was thinking, so the username and password could be extracted into a service object with something like a $scope.model = MyService.getModel() massive amount of pseudocode there – user1383163 Oct 01 '15 at 13:37
  • If i understand the different correctly factories are singletons and services are instances so for the models i want services and the rest requests factories. – user1383163 Oct 01 '15 at 13:38
  • Yes without knowing the exact workings of your app, that's most likely what I would do. – aw04 Oct 01 '15 at 13:38
  • This post will explain the differences better than I could hope to - http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory – aw04 Oct 01 '15 at 13:39
  • Sure, just remember not to over do it as the abstractions aren't always necessary/practical, but for almost any non trivial app they will be vital in places – aw04 Oct 01 '15 at 13:42