0

Creaed this service but getting an undefined object error. So the object is null but why, I feel like I'm doing it right.

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

app.factory('RollerService', function() {
    var rollers = [
        'roller1',
        'roller2',
        'roller3'
    ];

    return {
        get: function() {
            return rollers;
        },
    };
});

app.controller('Index', ['$scope',function($scope,RollerService) {
    $scope.rollers = RollerService.get;
}]);

TypeError: Cannot read property 'get' of undefined

Beginner in overall Javascript so some explanation would be nice.

1 Answer 1

2

You haven't injected your RollerService:

app.controller('Index', ['$scope', 'RollerService', function($scope, RollerService) {
  $scope.rollers = RollerService.get;
}]);

Angular's dependency injection tries to be smart by analysing the name of your function parameters. However, in order to protect against issues caused by code mangling (which turns parameter names into obscure names like a, b, etc), you need to explicitly annotate your functions by listing dependencies as strings, before defining the function itself.

Read more:

Once you understand how Angular's dependency injection works, you can use a tool like ng-annotate to save you from having to manually set $inject.

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

4 Comments

I thought I injected it zith the 'RollerService' in the function parameters? Why does it need to be defined twice?
I think you can just use app.controller('Index', function($scope, RollerService) {..., but this won't work if you minify your code.
@Arg0n - that's right, it will work when you minify, but it won't if your minification mangles too.
I see. In either case, you can't MIX defining parameter names and not, choose one and stick to it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.