javascriptangularjsfrontendangularjs-factoryangularjs-module

(AngularJS) Can't inject factory into controller


I'm trying to inject my factory into a controller. If I list the factory as one of the controller's parameters, I get this error:

Error: [$injector:unpr] Unknown provider: wordRushFacProvider <- wordRushFac <- wordrushCtrl
http://errors.angularjs.org/1.6.1/$injector/unpr?p0=wordRushFacProvider%20%3C-%20wordRushFac%20%3C-%20wordrushCtrl

Here is the code for my factory:

(function() {
    "use strict";

    angular
    .module("wordrush")
    .factory("wordRushFac", function($http) {

        function getValidWords() {
            return $http.get('../data/valid-words.txt');
        }

        return {
            getValidWords : getValidWords
        }
    })
})

And the code for my controller:

(function() {
    'use strict'

    angular
    .module('wordrush')
    .controller('wordrushCtrl', function($scope, $http, wordRushFac) {

        wordRushFac.getValidWords().then(function(words) {
            $scope.words = words.data;
        });
        $scope.words = 'Hello'
    });
})();

And for my index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Word Rush</title>

        <link rel="stylesheet" href="node_modules/angular-material/angular-material.css">
        <link rel="stylesheet" type="text/css" href="css/style.css">

        <script src="node_modules/angular/angular.js"></script>
        <script src="scripts/app.js"></script>
        <script src="components/wordrush.ctr.js"></script>
        <script src="components/wordrush.fac.js"></script>
    </head>
    <body ng-app="wordrush" ng-controller="wordrushCtrl">
        <h1> {{ words }} </h1>
    </body>
</html>

And for my app.js:

angular
.module('wordrush', ['ngMaterial'])
.config(function($mdThemingProvider) {

    $mdThemingProvider.theme('default')
    .primaryPalette('blue')
    .accentPalette('green');
})

I made a program with code identical to this except the names and variables were changed, and it worked fine. So what am I doing wrong here?


Solution

  • Here is a plunkr that says "Hello": https://plnkr.co/edit/MyxcXQ8YI4QYqeFsyVJz?p=preview

    You have an extra set of open / close parenthesis in your controller definition, remove those:

    angular
    .module('wordrush')
    .controller('wordrushCtrl', function($scope, $http, wordRushFac) {
    
        wordRushFac.getValidWords().then(function(words) {
            $scope.words = words.data;
        });
        $scope.words = 'Hello'
    });
    

    Also, are you sure you are including the ng-material JS file? I didn't see that listed in your HTML.