Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for persisting $scope between routes

Tags:

angularjs

I find that I almost always want to persist scopes across route changes, and because of this, I find that I've pretty much stopped using controllers, for anything other than forwarding everything to a service. My Controllers all end up looking something like this:

app.factory('CtrlAService', function() {
    return {
        scope: {},
    };
});

function CtrlA($scope, CtrlAService) {
    $scope.data = CtrlAService.scope;

}

That is to say, all that my controller does is bind a variable to a service variable, and other than binding a function or two - I don't use controllers for anything.

Is this approach correct, and if not, what is a better way to accomplish this?

I've made an example application here: http://jsfiddle.net/Wc22k/1/

like image 741
mindvirus Avatar asked Nov 01 '22 16:11

mindvirus


1 Answers

I think this is generally sort of true if you have a data heavy application. The more you need functionality for the views the more you end up with in your controllers. For instance I'm using google-maps and ng-grid within an application pretty extensively so all of my controllers contain all the configuration (sometimes functions for label display etc.) inside of controllers. Also the google-maps code I found and have been modifying (MIT Licensed) has a pretty complex JavaScript object that wraps the google maps code and a controller for the directive.

So short version, yes in a data heavy application most of your code ends up in services and the controllers are just hooking up the view to some data from a service, in other cases no. I see what you're saying about persisting scope but I think it's best to leave all the logic that is necessary for the view in the controller (I see this as the views model as opposed to the data model in the service). It just keeps a clear separation of what is going on where and what is affecting what. For example if I need to persist a piece of data between some views I store it in the service (have been considering using a "value" instead since it's more semantically and functionally appropriate but just haven't taken the time to do this re-factor).

like image 63
shaunhusain Avatar answered Nov 08 '22 04:11

shaunhusain