简体   繁体   中英

Separation of concerns in angular, when to use a service and/or factory?

I've been getting to grips with Angular lately and trying to get my head round the concepts that it's built on. All a little cryptic so far but I'm getting there!

Anyway so I've built a small part of my web site using Angular (it seemed to fit the use case as I needed to manipulate a JavaScript object on the browser).

As part of this process I needed to make add an object to my model (on click of an element). It took me a while to figure out how to do this but eventually I got it working.

Now I ended up with the code below:

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

stpApp.controller('multiStopController', function ($scope, $compile, $http) {
    $scope.inboundJourney = [{
        'DepartureAirport': '',
            'DestinationAirport': '',
            'DepartureDate': '',
            'DepartureTime': 9,
            'Class': 'Class'
    }];

    $scope.addInboundJourney = function () {
        $scope.inboundJourney.push({
            'DepartureAirport': '',
                'DestinationAirport': '',
                'DepartureDate': '',
                'DepartureTime': 9,
                'Class': ''
        });
    }
});

and some mark up:

<li ng-repeat="journey in inboundJourney">
    <input type="text" class="AirportName" ng-model="journey.DepartureAirport" />
</li>
<p class="addMultiStop"><span title="Add a journey" ng-click="addInboundJourney()">+</span>
</p>

Doing a little more reading I've seen the concepts of services and factories getting introduced. So should my addInboundJourney function be in a service or a factory, or is it ok in the controller, like it is now?

If this is ok in the controller, when is it advised to use a service and/or factory?

That's quite the subjective question. Move your inboundJourney manipulation into a service if you need to handle the manipulation in more than one controller, and inject it into the controllers.

If you're only ever going to manipulate the inboundJourneys in the multiStopController, then I'd say you're good to go on as you were.

If however you find that there's alot of code for the inboundJourneys manipulation (you might want to do some other things in the multiStopController aswell, making your controller fat), then I'd move it out into a service - regardless of how many controllers I aim to use the functionality in.

Separation of concerns in mind, it is best to create a service or a factory to represent an InboundJourney object. This object will also have methods for manipulating the data, eg addInboundJourney(journey) .

Which one to use is up to you - generally speaking, factory is used when pre-initialization code is required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM