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...

3 Answers 3

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.

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

1 Comment

Incidently, I provided an answer to the "Service vs. provider vs factory" SO question:)
1

There is nothing wrong with two factories using eachothers services.

Comments

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>

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.