Dennis
Dennis

Reputation: 368

Acces data from service in angularjs

I have a service where I pass some data on click what works great, but now I wanna pull that data from the service and add it to a scope in another controller and just log everytime there is something added with the $watch function.

My service:

app.service('infoService', function() {
    var currentInfo = [];
    return this.method = function(data){
        return currentInfo = data;
    };
});

Where I try to pull the data

app.controller('clickController', function($scope, infoService) {
    $scope.data = infoService.method();
    $scope.$watch('data', function(newVal, oldVal) {
        console.log(newVal, oldVal);
    });
});

The only thing I currently see the last hour are errors and errors.

Upvotes: 1

Views: 40

Answers (2)

therebelcoder
therebelcoder

Reputation: 1018

Try putting the watch on the return value of the service, like this:

$scope.$watch(function () { return infoService.method(); }, function(newVal, oldVal) {
        console.log(newVal, oldVal);
    });

Upvotes: 1

murnax
murnax

Reputation: 1222

Can you remove the return statement from your service

this.method = function(data){
    return currentInfo = data;
};

then you should be able to call function in your service

hope this helps.

Upvotes: 1

Related Questions