0

I am new to angular. I have a service where I call a function by another function within the service. But in my controller is shows as undefined. See below

//my Service
myApp.service("LocationService", function() {
    var srv = {}
    srv.msg = {long:0, lat:0};

    srv.onSuccess = function() {
        this.msg.lat = 32;
    },

    srv.onError = function() {
        this.msg.long = 99;
    },

    srv.getGpsFix = function() {
        this.onSuccess();//fails in controller
    }

    return srv;
});

//my Controller
myApp.controller("MusicCtrl", ["$scope", "LocationService", function($scope, LocationService) {

//undefined
    console.log(locationService.getGpsFix());

}]);
4
  • 1
    Terminate your function assignments with semicolons. So instead of srv.onSuccess = function() { /* ... */ },, do srv.onSuccess = function() { /* ... */ };. Commented Feb 14, 2015 at 7:32
  • @Jackson this should be an answer. Commented Feb 14, 2015 at 7:33
  • @Jackson I changed to semicolons at the end but I still get the undefined result. output of call console.log(LocationService.getGpsFix()); //undefined console.log(LocationService.msg); //lat is changed to 32 Commented Feb 14, 2015 at 7:44
  • Sure. I recommend that, in general, you use semicolons to terminate statements. My original suspicion was that that was the cause of the error, because frequently poor line termination is the cause of errors, but for this issue I think my posted Answer should help you. Commented Feb 14, 2015 at 7:46

2 Answers 2

1

It is correct that locationService.getGpsFix() would return undefined.

If you intended for it to return a value, then use the return keyword in your function.

srv.getGpsFix = function() {
    this.onSuccess();
    return 'It worked!!!';
};
Sign up to request clarification or add additional context in comments.

Comments

1

locationService.getGpsFix() is undefined. In your controller, your service is available as LocationService. Hence, use LocationService.getGpsFix()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.