What is the solution for fixing the [$injector:unpr] error in AngularJS?

I've recently started learning AngularJS and I'm encountering an issue with injecting a service from another file. Despite trying various methods, nothing seems to be working.

Here's a snippet from my index.html:

` <!DOCTYPE html>
<html ng-app="employeedirectory" ng-controller="homeController as vm">

<head>
    <title>Employee Directory</title>
    <link type="text/css" rel="stylesheet" href="./../bootstrap.min.css" />

</head>

<body>
    <div class="container" >
        <br/>
        <h1 align="center">Employee Directory</h1><br/><br/>
        <table class="table">
            <thead>
                <tr>
                    <td>Name</td>
                    <td>Email</td>
                    <td>Date of Birth</td>
                    <td>Department</td>
                    <td>Gender</td>
                    <td>Age</td>
                </tr>
            </thead>

            <tbody>
                <tr>

                    <form>
                        <td>
                            <input class="form-control" ng-model="employee.name" required placeholder="Name" />
                        </td>
                        <td>
                            <input type="email" ng-model="employee.email" required class="form-control" placeholder="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33525150734b4a491d505c5e">[email protected]</a>" />
                        </td>
                        <td>
                            <input type="text" ng-model="employee.dob" id="datepicker" class="form-control" required placeholder="YYYY-MM-DD" />
                        </td>
                        <td>
                            <input ng-model="employee.department" required class="form-control" placeholder="Department" />
                        </td>
                        <td>
                            <input ng-model="employee.gender" required class="form-control" placeholder="Gender" />
                        </td>
                        <td>
                            <input type="number" ng-model="employee.age" disabled class="form-control" placeholder="Age" />
                        </td>
                        <td>
                            <button class="btn btn-primary btn-md" ng-click="vm.addEmployee()">Add Employee</button>
                            <td><button class="btn btn-info btn-md" ng-click="updateEmployee()">Update Employee</button></td>
                        </td>

                    </form>
                </tr>


            </tbody>

        </table>
    </div>

    <script src="./../angular.min.js"></script>

    <script src="./home.controller.js"></script>
</body>

</html>`

Below is a snippet from my controller:

(function () {
    'use strict';

    angular.module('employeedirectory', [])
        .controller('homeController', ['homeService',homeController]);

    function homeController() {
        var vm = this;
        vm.addEmployee = function () {
            console.log("in add employee");

            // homeService.addEmployee();

        }
    }
})();

This snippet pertains to my service:

(function () {
    'use strict';
    angular
        .module('employeedirectory')
        .service('homeService', homeService);


    function homeService() {
        // var service = {};

        // service.addEmployee = function (details) {
        //     console.log("in home service");
        // };
        // return service;
    }
})();

The error message I am currently facing:

angular.min.js:123 Error: [$injector:unpr] http://errors.angularjs.org/1.6.4/$injector/unpr?p0=homeServiceProvider%20%3C-%20homeService%20%3C-%20homeController
    at angular.min.js:6
    at angular.min.js:45
    at Object.d [as get] (angular.min.js:43)
    at angular.min.js:45
    at d (angular.min.js:43)
    at e (angular.min.js:43)
    at Object.invoke (angular.min.js:43)
    at S.instance (angular.min.js:94)
    at n (angular.min.js:69)
    at g (angular.min.js:61)

Answer №1

Make sure to include a reference to your service in the index.html file.

<html>
<head>
    <title>Employee Directory</title>
    <link type="text/css" rel="stylesheet" href="./../bootstrap.min.css" />

</head>
<body>
    //  .....
    <script src="./../angular.min.js"></script>
    <script src="./home.controller.js"></script>
    <script src="./homeService.js"></script>
</body>

By adding this reference, the controller will be able to properly inject your service.

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

Looking to access XML file data using Vue.js on the server side?

I am trying to access an XML file located in a specific path on the server side using VueJS without using jQuery. Can you provide me with some ideas or advice? Scenario: 1. The file is stored at /static/label/custom-label.xml. 2. I need to read this file ...

What sets apart an exception from a promise left unfulfilled?

As I delve into the topic of error handling, I came across an interesting concept in my reading material. The literature explains that if a throw statement occurs within a Promise's catch function, it is considered a rejection. It draws a distinctio ...

Adjusting the width of the dropdown menu in Angular UI

I have set up an Angular UI dropdown list in this plunk, where the selection list has a maximum height and allows for scrolling. However, I am having trouble setting a maximum width for the list. Can anyone suggest how to solve this issue? Below is the HT ...

Utilize the clearChart() function within Google charts in conjunction with vue-google-charts

I have integrated vue-google-charts to display various charts on my website. I want to allow users to compare different data sets, by enabling them to add or delete data from the chart. In order to achieve this functionality, I need to find a way to clear ...

Perform a MongoDB find() query using the _id field as the search criteria

So I am currently working on my express app and I need to find data based on the _id field in MongoDB. Below is a snippet of my MongoDB record: { "_id": { "$oid": "58c2a5bdf36d281631b3714a" }, "title": "EntertheBadJah" ...

Unordered list in Bootstrap Collapse not responding after initial click

I recently created a filetree page on my website and incorporated some bootstrap collapse elements that seem to function as intended. However, I am encountering an issue where the folder content does not collapse upon clicking the folder symbol (button) fo ...

How can I maintain focus selection while replacing HTML with text in a contenteditable div without losing it?

When working with a div tag that needs to be editable, the goal is to prevent users from entering any HTML into the tag. However, despite efforts to restrict input, when users copy and paste content, it often includes unwanted tags. To address this issue, ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Utilizing Angular 2's Routerlink with *ngIf and Parameters

Currently, I am facing an issue with a routerlink that includes a parameter: http://localhost:4200/item/1 I am trying to figure out how to implement an *ngIf statement with a parameter.... Here is what I have attempted so far: <div *ngIf="router.url ...

What is the recommended method for obtaining the maximum suggested number for the y-axis?

How do I determine the suggestedMax value for the yAxes scale? For instance, in the provided image, it is 4000 for legend2 and 400 for legend1) Legend Label 1: https://i.sstatic.net/ZfVSz.png Legend Label 2: https://i.sstatic.net/l05ar.png var canva ...

Having trouble fetching AJAX POST data in PHP?

Attempting to send a variable as an object to my PHP file, but it's not receiving any data. Testing with window.alert(u.un) in the AJAX call shows that data is being passed successfully without errors in the console. However, the PHP file still does n ...

Exploring various templates with AngularJS Directives

Let's delve into a slightly complex topic, but I'll simplify it as much as possible for you. There is a directive in play: .directive('configuratorRows', function () { return { restrict: 'A', scope: { ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

When moving a div with jsPlumb, the id is unable to be dynamically inserted from an AngularJS binding

While implementing my flowgraph using jsPlumb to enable node dragging and node connections, I encountered a persistent error related to the dragging functionality. Every time I attempt to drag a node, an error message is logged in the console for each pix ...

Leveraging recompose utility within the structure

I am exploring the use of recompose utility functions as a React element, enabling me to incorporate them into JSX as higher-order components (HOC). const enhancedInput = props => { return (<OnlyUpdateForKeys keys={['name']> ...

Various web browsers may exhibit varying behaviors when processing extremely lengthy hyperlinks

I am curious to understand why browsers handle long URLs differently based on how they are accessed. Let me explain further: Within my application, there is a link to a specific view that may have a URL exceeding 2000 characters in length. I am aware that ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...

Using JQuery Slider to call a function without the need for an ID, instead utilizing the object directly

Currently, I am working on implementing a Slider using JQuery, and I have encountered an issue in my code. The function is set to run when the page loads, creating a slider with the Id specified in the div element: $(function() { $( "#slider& ...

Error in Angular Google Maps Component: Unable to access the 'nativeElement' property as it is undefined

I am currently working on creating an autofill input for AGM. Everything seems to be going smoothly, but I encountered an error when trying to integrate the component (app-agm-input) into my app.component.html: https://i.stack.imgur.com/mDtSA.png Here is ...

Asynchronous JavaScript function within a loop fails to refresh the document object model (DOM) despite

I have been working on a function that utilizes ajax to retrieve instructions from a backend server while the page is loading. The ajax code I've written retrieves the instructions based on the number provided and displays them using the response.setT ...