Bummer! You have been redirected as the page you requested could not be found.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Seth Warner
Seth Warner
1,878 Points

Angular question: I would love to know how to make use of a service in a controller, if the service is stored in..

A separate file.

Let's say I have this code, how would I need to alter my controller file, in order to make use of the service if it was not chained directly on the controller, but stored in a folder, named services, and that service was in its own file named "honingService".

angular.module('HoningNow', [])
.controller('HoningnowController', function ($scope, honingService) {
    $scope.honingNow = honingService.honingNow;


})

.service('honingService' function () {
this.honingNow = [

       {
          { "name" : "Yeoman" },
          { "name" : "Sass" },
          { "name" : "D3" },
          { "name" : "Browserfiy" },
          { "name" : "Protractor" },

       }


    ];

});

1 Answer

Balázs Buri
Balázs Buri
8,799 Points

Your original file would look like this:

angular.module('HoningNow', [])
.controller('HoningnowController', function ($scope, honingService) {

    $scope.honingNow = honingService.honingNow;


});

And your new file like this:

angular.module('HoningNow').service('honingService' function () {
this.honingNow = [
       {
          { "name" : "Yeoman" },
          { "name" : "Sass" },
          { "name" : "D3" },
          { "name" : "Browserfiy" },
          { "name" : "Protractor" },
       }
    ];
});

the only difference here is that in the new file you use angular.module again but this time without the second parameter, dependencies. This way you tell angular to use that existing module and add your new service to it. Obviously you can't use method chainig like this: angular.module('module', []).controller().service() because your code is in two files now.

Now however you need to include both files in your index.html <head> tag

Seth Warner
Seth Warner
1,878 Points

Thanks @Balázs Buri , Much appreciated!