Jacob Valenta
Jacob Valenta

Reputation: 6769

AngularJS Controllers inside controllers

I have been working with AngularJS recently, and I feel I may be thinking about the paradigm wrong.

I have a pane controller (tied to an ng-repeat) which keeps track of which "panes" the user has open. Now each of these panes are to have data in them, which means almost all of them would have another controller inside of them.

I read one answer here (with a similar situation) in which the answer suggests rewriting their "popup" controller as a service.

The pane controller:

app.controller('PaneCtrl', function ($scope, PaneService){
    var updatePanes = function(panes){
        $scope.panes = panes;
    }

    // subscribes this controller to the Pane Service
    PaneService.registerObserverCallback(updatePanes)
});

Service

app.factory('PaneService', function(){
    var observerCallbacks=[]
    var panes = []

    var notifyObservers = function(){
        angular.forEach(observerCallbacks, function(callback){
            callback(panes);
        });
    }

    return {
        createRootPane: function(title, meta, data){
            // do stuff
        },

        toggleSearchPane: function(){
            // do stuff
            notifyObservers();
        },

        registerObserverCallback: function(callback){
            observerCallbacks.push(callback);
        }
    }
});

My question is what is the best practice here, and if the best practice is "rewrite this as only a service", what would that service look like?

Upvotes: 2

Views: 224

Answers (1)

koolunix
koolunix

Reputation: 1995

I Would suggest you rewrite this as a directive and make the model <=> view association within the directive's controllers.

There's a tab example in the Angular documentation on directives in the Angular Documentation under Creating Directives that Communicate. If you are getting data to populate scope from an outside data source, or using caching use a factory.

Upvotes: 2

Related Questions