Aidan Gee
Aidan Gee

Reputation: 579

simple angular service confusion

To put it simply angular services always confuse me and I seem to get them working by trial and error. I'd like to know why in this case data returns undefined.

App module :

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

Service:

//creating a service module
var appServices = angular.module('services', []);

appServices.factory('Data', function(){
return {message : "I am data"}
});

Controller:

app.controller('firstCtrl',['Data',
function($scope, Data){
    //get data from the service
    $scope.data = Data;
    console.log(Data);

}]);

app.controller('secondCtrl',['Data',
function($scope, Data){
    //get data from the service
    $scope.data = Data;

}]);

If I console log data I just get "undefined" . Im just trying to do a simple example to return the object {message:"i am data"} so that

$scope.data = Data;

then in the view

data.message = "i am data"

Would really appreciate an explanation of why this does not work. Thanks

Upvotes: 1

Views: 109

Answers (2)

suresh pareek
suresh pareek

Reputation: 98

you can use above answer but you can use

app.controller('firstCtrl', function($scope, Data){

    //get data from the service
    $scope.data = Data;
    console.log(Data);
});

this will work fine no need for passing array of services and function in controller as second argument just function will work fine.

Upvotes: 0

James Allardice
James Allardice

Reputation: 166021

You're not injecting $scope into the controller. Change it to this:

app.controller('firstCtrl', [
    '$scope', // There should be an element of this array for each parameter
    'Data',
    function($scope, Data){
        //get data from the service
        $scope.data = Data;
        console.log(Data);
    }
]);

As you're only injecting the Data service it gets mapped to the $scope parameter of the controller function, and nothing gets mapped to the Data parameter (and since a variable that has not been assigned a value implicitly has the value undefined, you see undefined).

Upvotes: 3

Related Questions