A controller in Angular.js that leverages several different services

I'm having trouble injecting multiple services into a controller. Here are my listed files:

index.html file:

<script src="'./angular/angular.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>
<script src="'./angular-route/angular-route.js'></script>
<script src='./app/app.js'></script>
<script src='./app/welcome/welcome.js'></script>
<script src='./app/controls/questions.js'></script>
<script src='./app/services/questionsdata.js'></script>
<script src='./app/services/getsong.js'></script>

console.log error:

Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=getsongProvider%20%3C-%20getsong%20%3C-%20QuestionsCtrl
    at Error (native)
    at http://localhost:8000/static/angular/angular.min.js:6:416
    at http://localhost:8000/static/angular/angular.min.js:43:7
    at Object.d [as get] (http://localhost:8000/static/angular/angular.min.js:40:270)
    at http://localhost:8000/static/angular/angular.min.js:43:69
    at d (http://localhost:8000/static/angular/angular.min.js:40:270)
    at e (http://localhost:8000/static/angular/angular.min.js:41:1)
    at Object.instantiate (http://localhost:8000/static/angular/angular.min.js:41:364)
    at http://localhost:8000/static/angular/angular.min.js:87:42
    at link (http://localhost:8000/static/angular-route/angular-route.js:977:26) <section class="container-fluid ng-scope" id="main" ng-view="">

My app.js file:

(function(){

    'use strict';

    angular.module('myApp', ['ngRoute', 'myApp.welcome', 'myApp.questions' ])

    .config(function ($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                redirectTo: '/welcome'
            })
            .when('/welcome', {
                templateUrl: 'static/app/welcome/welcome.html',
                controller: 'WelcomeCtrl'
            })
            .when('/questions', {
                //templateUrl: 'static/app/questions/questions.html',
                templateUrl: 'static/app/views/questions.html',
                //controllerAs: 'question',
                controller: 'QuestionsCtrl'
            })
            .otherwise('/')
    });

})();

My controller file:

(function () {

    'use strict';

    angular
        .module('myApp.questions', ['ngRoute', 'ngSanitize'])
        .controller('QuestionsCtrl', QuestionCtrl);

    function QuestionCtrl(questionsdata,getsong) {

        var vm = this;

        var data = {
            params: "1,1"
        }; 
....

My questionsdata (first service) file:

(function () {

    'use strict';

    angular
        .module('myApp.questions')
        .factory('questionsdata', questionsdata);

    function questionsdata() {

        var service = {
            getQuestions: getQuestions
        };


        return service;
.....

My get song (second service) file

(function () {
    'use strict';

    angular
        .module('myApp.questions')
        .factory('getsong',getsong);

    function getsong($http, $window, $interval) {

        var service = {
            getId: getId,
            getMySong: getMySong
        };

        return service;
....

It seems like the setup is not working properly.

When I modify my controller file to use only the questionsdata service as follows:

'use strict';

    angular
        .module('myApp.questions', ['ngRoute', 'ngSanitize'])
        .controller('QuestionsCtrl', QuestionCtrl);

    function QuestionCtrl(questionsdata) {

It works fine. But when attempting to use only the getsong service as follows:

 'use strict';

    angular
        .module('myApp.questions', ['ngRoute', 'ngSanitize'])
        .controller('QuestionsCtrl', QuestionCtrl);

    function QuestionCtrl(getsong) {

It doesn't work either. Strange, right? What could be the issue?

Answer №1

Consider utilizing the inject function:

 'use strict';

    angular
        .module('myApp.questions', ['ngRoute', 'ngSanitize'])
        .controller('QuestionsCtrl', QuestionCtrl);

    QuestionCtrl.$inject = ['getsong', 'questiondata'];

    function QuestionCtrl(getsong, questiondata){

Answer №2

For your index.html file, consider including the following scripts:

<script src="'./angular/angular.min.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>
<script src="'./angular-route/angular-route.js'></script>

<script src='./app/controls/questions.js'></script>
<script src='./app/welcome/welcome.js'></script>
<script src='./app/app.js'></script>    
<script src='./app/services/getsong.js'></script>
<script src='./app/services/questionsdata.js'></script>

It is important to note that myApp relies on both myApp.welcome and myApp.questions, so make sure to load them first.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transform JavaScript object into desired structure

let obj = { "rec": [{ "id": "25837", "contentId": "25838" }, { "id": "25839", "contentId": "25838" }, { "id": "25838" }, { "id": "25 ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

Identifying Changes in Form Values Using jQuery

I am facing a challenge with a dynamic form that needs to detect the field sequence properly. Below is my JavaScript file: var i = 1; $("a.add-line").click(function(){ $("div.items").append( $('<div>').attr('id',&ap ...

It is not possible to assign values to a typed array buffer

Why is the value not being assigned as anticipated without any errors being thrown? const fs = require('fs'); let file = "data.dat"; let readStream = fs.createReadStream(file,{highWaterMark:1024*1024*128}) let stats = fs.statSync(file); let stre ...

How to Extract Minutes in Datatables Timestamps and Apply Custom Styling

Working with Datatables v1.10 Right now, my table is showing a date in the second column in the format 17-04-2019 14:34, which is how it's stored in the database. The filtering and searching functionality are all working as expected. The current HTM ...

Leveraging onClick in combination with React's AutoBind

Just started learning React, so please point me towards documentation if I missed anything. I'm attempting to initiate an Ajax call using the onClick method following a tutorial on React. See the code snippet below. doSomething: function() { // ...

"Troubleshooting: Jquery Draggable Function Fails to Execute

I'm currently working on a JSP page where I am attempting to make the rows of a table draggable. Despite multiple attempts and combinations, I have been unable to make any elements draggable. The rows are appended after an AJAX call, but still no succ ...

Redis Recursion: The callstack has reached its maximum size limit

Looking for some assistance with creating a game timer. I've decided to utilize Redis and Web Sockets in order to synchronize the timer across multiple devices. However, I'm running into an issue when trying to call my function recursively using ...

Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview OR ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

When the visitor is browsing a particular page and comes across a div element, carry out a specific action

I am trying to determine if I am currently on a specific page and, if so, check if a certain div exists in that page. Here is what I know: To check if a specific page exists, I can use the code if('http://'+location.hostname+location.pathname+& ...

Refreshing webpage content by utilizing iframes

I am looking for a way to completely clear a webpage using either Javascript or PHP. However, there seems to be an issue with a specific area of the page that is marked as: data-form="manual iframe" When attempting to clear the page, only the data within ...

Pass an object along with the rendering of the page using ExpressJS and Mongoose

After reading through this post: mongoose find all not sending callback I am currently working on sending an Object along with a page in my nodejs/expressjs application, instead of just responding with JSON data. This is the route for my page: //Get lat ...

NodeJS/ExpressJS API exposure

Currently, I am developing a website using Express and implementing route handling with the help of express router. The routes I have set up so far include registration, login, upload, and more. One particular route, upload, requires files to be uploaded ...

Retrieving precise passed arguments in the $(document).ready function

I am working on a gridview where I need the rows to expand and display the BatchID that is passed. Currently, I am using href="javascript:switchViews('div<%# Eval("BatchID")%>', 'one');" to pass this information, but I'm stru ...

Get the Label Values Based on CheckBox Status

Is there a way to retrieve the values of labels corresponding to checkboxes in HTML? I have multiple labels and checkboxes next to each other, and I want to be able to get the label values if the checkbox is checked. Can you provide guidance on how to do ...

Split a string containing integer and decimal values into an array

I encountered an issue when converting a string to an array: var data = "[[1, 2, 3,], [3, 2, 1]]"; var array = JSON.parse(data.replace(/,\s*]/g, ']')); This problem arises when handling floating point numbers in the input: var data = "[[2 ...

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...

The function, stored as state within a context provider, is experiencing only one update

I am facing an issue with my Next.js and Typescript setup, but I believe the problem is more general and related to React. Despite extensive research on Stack Overflow, I have not come across a similar problem. To provide some context: I have a <Grid&g ...

HTML image identifier and canvas elements

Greetings! I have a question that I've been struggling to find an answer for on Google. I'm attempting to draw an image on a canvas and initially used the "new" constructor ( ballPic = new Image(); ballPic.src = "ball.png" ) which worked fine. Ho ...