Strat-O
Strat-O

Reputation: 163

Can't attach angularjs service to controller

I'm getting this error when I try to attach a service to a controller: [$injector:unpr] ... webSocketServiceProvider <- webSocketService <- videoMenuCtrl

I have a plunker defined with a fairly minimal setup that reproduces the problem:

http://plnkr.co/edit/ptaIaOhzOIG1mSi4bPyF?p=preview

Here are the main culprit files:

index.html:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>title</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  </head>
  <body ng-app="videoApp">
    <section class="menu" ng-controller="videoMenuCtrl">
    </section>
    <script src="webSocketService.js"></script>
    <script src="videoMenu.js"></script>
    <script src="ngDialog.min.js"></script>
    <script src="ngPopup.min.js"></script>
</body>
</html>

webSocketService.js:

(function(angular) { 
    'use strict';

angular.module('videoApp')
    .factory('webSocketService', function($q) {
    return{};
});
});

videoMenu.js:

'use strict';

var app = angular.module('videoApp', ['ngDialog', 'ngPopup']);

app.controller('videoMenuCtrl', function($scope, $window, $location, ngDialog, webSocketService) {

});    

I don't get an error if I remove the webSocketService from the controller, but the point is to have the controller be able to access the webSocketService. Any ideas? Thanks!

Edit: Changed file name typo.

Upvotes: 0

Views: 234

Answers (1)

Ben Harold
Ben Harold

Reputation: 6432

I got your code working. Two things I noticed:

  1. In you webSocketService.js you were re-declaring the videoApp module.
  2. You were declaring the module inside a function expression that was not being invoked.

I re-declared your service in a properly namespaced module and wrapped it in an immediately invoked function expression.

I also removed your var app = declaration from your videoMenuCtrl and wrapped it in an IIFE as well. This is to avoid cluttering the global namespace. Here is a working plunk:

http://plnkr.co/edit/A8BcATiaqhXCA7BZDXWx?p=preview

EDIT (clarification) The IIFEs are not strictly necessary in my example plunk because the var app = declaration was removed from the code. That was the only variable that was being declared on the global namespace in the original example. However, wrapping the code in IIFEs has no negative effects as far as I know.

Upvotes: 1

Related Questions