0

I am trying to create a base controller where I can use functions that all of the other controllers need together. I want to inherit or instantiate the JavaScript page on my lower controllers.

I looked online and saw different suggestions but it hasn't worked for me. I have put the 2 scripts in order on the layout. I created a base controller:

var app = angular.module('mainApp', []);

I am trying to access it int he other controller:

    baseController.app
   .controller('listsController'.....

How do I get access to the baseController (which will in the future have functions) in my listController file?

David Tunnell
  • 7,252
  • 20
  • 66
  • 124

1 Answers1

2

One way is to use the $controller service to instantiate it like this answer states

app.controller('ChildCtrl', function($scope, $controller) {
  $controller('ParentCtrl', {$scope: $scope}); 
});

But as you say that you have functions that all of the other controllers need I suggest you to create a service which will hold these common functions instead.

Here's an service example:

app.factory('functionServ', function () {

    var function1 = function(){
        //Do your thing
    };

    var function2 = function(){
        //Do your thing
    };

    return {
        function1: function1,
        function2: function2
    }
});

Then inject the service in the controllers which need to use the common functions

app.controller('ChildCtrl', ['$scope', 'functionServ',  
    function ($scope, functionServ) {

    //Call the functions like: functionServ.function1();
}]);
Community
  • 1
  • 1
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69