Kimy BF
Kimy BF

Reputation: 1079

Difference between using a service and a controller in Angular

Its my first first time using javascript and angular. So Im developing a web page with angular, and I wrote a Controller like this:

 /*BrandController to manage the html content of a single brand */
 .controller('BrandController', [function(){
    this.brand = {};

    this.isSet = function(checkBrand) {
        return this.origin === checkBrand;
    };

    this.setBrand = function(activeBrand) {
        this.brand = activeBrand;
    };

 }])

I have some tabs of brands and when I click one, that brand is assigned with the controller.

<a href ng-click="BrandController.setBrand(brand)">
        <h4>{{brand.name}}</h4></a>

And I show its content like this:

<b>Nombre</b><br>
{{BrandController.brand.name}}<br><br>
<b>Marca</b><br>
{{BrandController.brand.brand}}<br><br>

So, It works the way I wanted, but a friend told me this was not the correct way to do it. That I have to create a service, to pass the information of brand. And we got it like this:

/* BrandController to manage the html content of a single brand */
 .controller('BrandController', function(BrandService, $scope){
    $scope.brand = {
    };
    $scope.setBrand = function(brand){
        $scope.brand = brand;
    };
    $scope.isSet = function(brand){
        return $scope.brand === brand;
    };

 })

 .service('BrandService', function(){
    var brand = {};

    var isSet = function(checkBrand) {
        return brand === checkBrand;
    };

    var setBrand = function(activeBrand) {
        brand = activeBrand;
    };

    return{
        isSet: isSet,
        setBrand: setBrand
    };

 });

This works too, as you can see is much more code, and I could not to understand why should I create a service instead. So, If you can explain in my example what is the best way to do it and why I would be very grateful.

Thank you.

Upvotes: 1

Views: 256

Answers (1)

rick
rick

Reputation: 1895

There are some situation while service are really usefull. with a service you can abstract the logic to read data keeping your controller standard. In case your data structure change you can change the logic in the service without touching the controller(and potentially the view).

The controller is responsible for binding data to the view and should not care about how the data are received or structurated.

Service are also singleton so you can store data cross controller or between controller and directives.

Most used application of those concepts are data services. here you can find a good documentation explaining the best practice and some logical advantages.

hope this helps

Upvotes: 1

Related Questions