Search code examples
angularjsangularjs-controllerangularjs-factory

Access angularjs controller from factory angularjs


We build a controller that holds all the $resource of our app for easier access from the controllers :

app.controller('ResourcesCtrl',  ['$scope', '$resource', '$controller', function ($scope, $resource, $controller) {

$scope.Product = $resource(resources_url_global + '/products/:id.json', { id: '@id' }, default_actions);

var default_actions = {
    'get': {
        method: 'GET'
    },
    'create': {
        method: 'POST'
    },
    'save': {
        method: 'POST'
    },
    'update': {
        method: 'PUT'
    },
    'update_all': {
        method: 'PUT'
    },
    'query': {
        method: 'GET',
        isArray: true
    },
    'remove': {
        method: 'DELETE'
    },
    'delete': {
        method: 'DELETE'
    }
};}]);

and an example of access from other controller:

app.controller('ProductsManagementCtrl',  ['$scope', '$controller', '$resource', 
    function ($scope, $controller, $resource) {
$controller('ResourcesCtrl', {$scope: $scope}); // inherit Parent Controller }]);

the problem is that i want to use that ResourceCtrl from a factory, but I don't know how to call it from the factory.


Solution

  • You should build it as a service and not as a controller.

    You can inject the service into other services and other controllers.

    If you really need a resource controller then simply inject the resource service and create a wrapper.