1

I would like to find out whether or not it is applicable to use two Factories in AngularJS and basically call one from the other.

Consider this Scenario:

I have a Factory returning an Array. This Factory is ought to verify whether or not Data to fill this Array is already in a local SQL Storage.

If TRUE it returns this Data back to my Controller.

If FALSE its supposed to call another Factory which consumes Data from a RESTful API. It then writes this Data to the WebSQL DB and finally returns this Data.

Does this Design follow standard Software-Patterns? I'm having a hard time to apply AngularJS Techniques to my Project...

Adrian MK
  • 173
  • 1
  • 2
  • 12

3 Answers3

3

It is completely fine to inject one service/factory/provider into another one.

Here is a very good answer when to use which one - AngularJS: Service vs provider vs factory

In this particullar scenario I would use your services as SQL service and API service. Controller only injects SQL service and sends data there. SQL service then determines what to do with data, if it needs to, it request additional data from API service which should return promise at first and return data on resolve. When SQL service is done it returns data to controller independetly of whether it called API service or not. Again preferrably using promise pattern. Controller does not need to know about API at all.

Community
  • 1
  • 1
Krym
  • 743
  • 6
  • 16
1

There is nothing wrong with two factories using eachothers services.

Michael Kang
  • 52,003
  • 16
  • 103
  • 135
1

AngularJS comes with a built-in dependency injection mechanism, which is all about sharing resources like in your case you want 2 factory to use each other I am putting a simple example here how to do it here is your angular script

var app = angular.module('yiiframe-factoryApp', ['ngRoute']);
 app.factory("myFactory1", function() {
    return "Controller";
});

app.factory("myFactory2", function(myFactory1) {
    return "factory" + myFactory1;
});
function factoryController($scope, myFactory2) {
    $scope.ctrlName = myFactory2;
}

and here goes your view

<div ng-app="yiiframe-factoryApp" class="container">
    <div ng-controller="factoryController" class="page-content">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">Angularjs Factory example</h3>
                </div>
                <div class="modal-body">
                    {{ctrlName}}
                </div>
            </div>
        </div>
    </div>
</div>
Kuldeep Dangi
  • 4,126
  • 5
  • 33
  • 56