0

I am not able to access a service inside my controller method.

AppController.$inject = ['$scope', 'appService'];
function AppController($scope, appService) {
    $scope.name = "World";

    $scope.clicked = function() {
      //am not able to access appService here
      /*
      appService.setName("john");
      $scope.name = getName();
      */
      $scope.name = "button clicked";
    }
}

http://plnkr.co/edit/UgHmtCbkxeyluTPJOG4T?p=info

The service is accessible when the controller gets created, but not when clicked() is called in the controller. Please let me know if I am missing something here.

I was trying to create a directive (something like a locale select dropdown). I wanted the directive to have its controller and its own service. My idea is that the controller would handle the languageChange() method when the user changes the dropdown and sets the language in a service, so that I can inject this service in any other part of the application.

That's when I had problems in accessing the service inside my controller method(languageChange())

I think if I get the basic example right, I will be able to proceed with my language change directive.

1 Answer 1

1

You forgot add the appService to getName()

Use this:

  appService.setName("john");
  $scope.name = appService.getName();

Instead of:

  appService.setName("john");
  $scope.name = getName();

Running example: http://plnkr.co/edit/Hh9g7H9PI9JhNdbAhqdT?p=preview

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

2 Comments

Thanks for the quick response. But I had other cases where appService was not accessible inside the controller method. Can you think of any reason ? I can access them when the controller starts up, but not when a method in the controller gets called. Also, can you post a very basic example which creates a directive, may be a button, which has a controller and service. On click of the button, I want to invoke a method in a controller, which talks to a service.
Hi @touchydeer36 if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.

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.