mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error:

Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl

My main goal is to display an ng-view on my index.html page.

Index.html

<div ng-view>

</div>

app.js

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider.

    when('/list', {
        templateUrl: 'app/views/list.html', controller: 'listCtrl'
    }).

    otherwise({
        redirectTo: '/list'
    });

}]);

websiteService.js

app.factory('webiteFactory', ['$http', '$location', function ($http, $location) {

    var factory = {};

    // method that return all websites from an http request
    factory.getAllWebsites = function () {
        return $http.get("http://localhost/Replicate/GetAllWebsites");
    }

    //method that returns an object from given array
    factory.getFilteredObject = function (list, websiteName) {
        for (i = 0 ; i < list.length ; i++) {
            if (list[i].Name == websiteName)
                return list[i];
        }
    }


    return factory;
}]);


/* application services that would not return values */
app.service('websiteService', ['$http', function ($http) {

    //service for pagination
    this.paginate = function ($scope) {

        //pagination code
        $scope.currentPage = 1;
        $scope.totalItems = $scope.model.length;
        $scope.numPerPage = 10;
        $scope.paginate = function (value) {
            var begin, end, index;
            begin = ($scope.currentPage - 1) * $scope.numPerPage;
            end = begin + $scope.numPerPage;
            index = $scope.model.indexOf(value);
            return (begin <= index && index < end);
        };


        //ordering code
        $scope.reverse = true;
        $scope.order = function (predicate) {
            $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
            $scope.predicate = predicate;
        };
    }

    //service to change state of a website
    this.changeSiteState = function (website) {
        var newState = website.State == "Stopped" ? "Started" : "Stopped";
        $http({
            method: 'POST',
            url: '/Replicate/ChangeState/',
            data: JSON.stringify({ webName: website.Name, state: newState }),
            headers: { 'Content-Type': 'application/json' }
        }).success(function (data) {
            if (data == "success") {
                website.State = website.State == "Stopped" ? "Started" : "Stopped";
            }
            else {
                alert(data);
            }

        }).error(function (data, status, headers, config) {
            alert(data);
        });
    }
}])

listCtrl.js

app.controller('listCtrl', function websiteCtrl($scope, $location, websiteFactory, websiteService, $modal) {

    //function triggered at the intialization of controller
    $scope.init = function () {
        $scope.model = [];
        setTimeout(function () {
            websiteFactory.getAllWebsites().success(function (data) {
                $scope.model = data;
                websiteService.paginate($scope);
            })
        }, 0);
    };

    //delegation of change state to service method
    $scope.changeState = function (website) {
        websiteService.changeSiteState(website);
    }

    //open modal and shows details of single object
    $scope.showDetails = function (websiteName) {
        var modalInstance = $modal.open({
            templateUrl: '../Views/Replicate/Details.html',
            controller: 'DetailsCtrl',
            resolve: {
                obj: function () {
                    return websiteFactory.getFilteredObject($scope.model, websiteName);
                }
            }
        });
    }

});

Answer №1

You have a spelling error in your code. The factory is defined as "webiteFactory" but you are trying to use it in the controller as "websiteFactory". This mismatch is causing an error because the provider cannot be found. Here is the corrected version:

app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {

    var factory = {};

    // method that returns all websites from an http request
    factory.getAllWebsites = function () {
        return $http.get("http://localhost/Replicate/GetAllWebsites");
    }

    //method that returns an object from a given array
    factory.getFilteredObject = function (list, websiteName) {
        for (i = 0 ; i < list.length ; i++) {
            if (list[i].Name == websiteName)
                return list[i];
        }
    }

    return factory;
}]);

Answer №2

When Angular displays that error, it usually means your factory hasn't been properly registered. Update the code to:

app.factory('websiteFactory', ['$http', '$location', function ($http, $location) {
    ...add your functionality here...
}

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

Error Message: Unexpected character "C" found in JSON response from Ionic 2 Http GET request

Trying to execute a GET request and extract data from the response. this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => { console.log(res.json()); }, (err) => { console.log(err); }); An error message ...

Enhancing Next.js Images with Custom CSS Styles

I am working with a Next.js component: import styles from '../styles/Navbar.module.css' import Image from 'next/image' export const Navbar = () => { <div> <Image className={styles["navbar-home-icon"]} ...

I am looking to implement a feature that will disable unchecked checkboxes based on certain conditions in a

Upon selection of an option from a dataset, an API call is triggered. The API response includes an object with a nested array, whose values are listed as checkboxes. Additionally, the API returns a key named choose(const name primaryMax) indicating the max ...

Interactive sidebar search component for Angular

Within my angular application, I have implemented a universal sidebar navigation directive that offers a variety of features, including a comprehensive search function for users (with multiple criteria, not just a simple text input). When a user performs ...

Optimal methods for integrating an Angular application within an AngularJS application

Our extensive AngularJS application was initially developed 3 years ago and continues to receive new feature updates. I am keen on ensuring that these new features are written using the latest version of Angular. Converting the entire codebase is not feasi ...

Issue encountered when attempting to insert data via node into MySQL database

As a new Node developer, I am in the process of building some initial applications. Currently, I am working on inserting records into a MySQL database using Node. Below is an example of my post method: router.post('/add',function(req,res){ c ...

Is there a way in Rollup.js to substitute a dependency package's imported module with a local file?

I am currently working on a JavaScript project that needs to be bundled using Rollup.js. The project depends on package A, which in turn relies on package B: "mypackage" ---import--> "A" ----import----> "B" My package ...

Getting the iframe onload event in an ASP.NET application

I have integrated ReportViewer to display SSRS reports on my .aspx page. However, since the ReportViewer is rendered as an iframe in the browser, I am looking for a way to trigger a JavaScript function every time the iframe loads. Using window.onload w ...

How to retrieve scope variable within the <script> element

I have a question about using angularjs. Here is the structure of my HTML: <html> <body ng-controller="datafileController"> <div class="container"> <center><h1>Datafiles</h1></center> ...

Verifying if a particular track is currently playing in the HowlerJS playlist

I am currently experimenting with a HowlerJS playlist code and would like to create a button that can detect if a specific song in the playlist is playing. When this button is clicked, I want it to hide a certain line of text. However, my knowledge on this ...

Establishing Redux States within the Provider (error: Provider encountering useMemo issue)

Exploring redux for state management has been a new journey for me. I am hoping it will help reduce API calls and increase speed, but I've hit a roadblock with an error that I can't seem to figure out. To troubleshoot, I created a simplified vers ...

When implementing asynchronous form control validation in Angular 2, several API requests are triggered

Can anyone help me with adding async validation using a FormControl? For every keypress, I am receiving multiple responses and it seems like an extra request is triggered whenever I type or remove a character in the form control. code-snippets.component.t ...

What is the process for configuring a server page within create-react-app for sending API requests?

As I dive into learning React using create-react-app, my latest project involves making an API request to an external source. Initially, I included this request in the front end of the app as I was working on building it out. However, now I realize the imp ...

The requested :id route could not be found using the findById() method in

Having trouble retrieving data using Insomnia from a specific ID in my collection. Below is the sample request URL. http://localhost:5000/todos/5dd295a49d5d7a0b7a399bbe However, when I access http://localhost:5000/todos/ without the ID, I can see all the ...

Encountering difficulties with showing contact images in phonegap using angularjs

In my project, I encountered an issue where I can fetch and display the contact photo using simple HTML and JavaScript. However, when I attempt to do the same using AngularJS model, I encounter an error. Below is the code snippet that I am struggling with: ...

“How can controllers from multiple modules be integrated into the markup using angular syntax?”

Here's this particular question on SO that suggests the possibility of utilizing controllers from different modules by defining specific tag attributes like: <div ng-controller="submodule1.controller1">{{ whatever1 }}</div> <div ng-con ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...

Can you explain the steps for creating a directive in Angular that wraps an input and displays an error message if the input is invalid?

As a complete novice in Angular, I might have the wrong approach to it. My goal is to develop a directive that encompasses an input within some standard HTML. It should connect the ng-model of the input to the parent scope (the controller's myForm sc ...

Tips for centrally zooming responsive images without altering their dimensions

I have created a custom jQuery and CSS function that allows an image to zoom in and out on mouseover while maintaining a constant box size. I modified an example code to suit my needs. Check out the demo here: https://jsfiddle.net/2fken8Lg/1/ Here is the ...