2

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.