touchydeer36
touchydeer36

Reputation: 152

AngularJS - Not able to access service in a controller method

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.

Upvotes: 0

Views: 559

Answers (1)

rnrneverdies
rnrneverdies

Reputation: 15657

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

Upvotes: 1

Related Questions