"Unidentified service error - Resolving a problem in an AngularJS application

var myApp = angular.module("MyApp", ['ngRoute']);

myApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        templateUrl: 'partials/cart.php',
        controller: 'ctrl',
        resolve: {
            categories: function(cartService){
                console.log('inside resolve categories')
                return cartService.getCategories();
            }
          }           
      }).
      otherwise({
        redirectTo: '/'
      });
}]);

myApp.controller('ctrl', function (categories, $scope) {    
  $scope.items = categories;    
});

myApp.service("cartService", function ($http, $q) {     
    this.getCategories = function () {
        var deferred = $q.defer();    
        $http.get('js/categories.js')
            .then(function (response) {
              deferred.resolve(response.data);
            });

       return deferred.promise;     
    }    
});

myApp.run(['$rootScope',function($rootScope){    
    $rootScope.stateIsLoading = false;
    $rootScope.$on('$routeChangeStart', function(e, current, pre) {
        $rootScope.stateIsLoading = true;
        var fullRoute = current.$$route.originalPath;
        if(fullRoute == '/')
        {
          console.log('load categoreis and products')  
        }            
    });
    $rootScope.$on('$routeChangeSuccess', function() {
        $rootScope.stateIsLoading = false;
        console.log('route changed');
    });
    $rootScope.$on('$routeChangeError', function() {
        //catch error
    });    
}]);

I have included the ng-app and ng-controller directives in the HTML structure

<html lang="en" ng-app="MyApp" ng-controller="ctrl">

However, upon running the HTML, an error message is displayed:

Error: [$injector:unpr] Unknown provider: categoriesProvider <- categories <- ctrl

I am seeking guidance on how to resolve this issue.

Edit: Removing the ng-controller="ctrl" from the HTML eliminates the errors.

Answer №1

The error occurred because you are using the same controller for both index.php and 'partials/cart.php'

To fix this issue, create a separate controller specifically for 'partials/cart.php'

Check out the updated code snippet below:

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

app.controller('indexCtrl', function($scope) { 
  $scope.title = 'Header';
});


app.config(function($routeProvider) {
  $routeProvider.when('/', {
    template: "<ul><li ng-repeat='item in items'>{{item}}</li></ul>",
    controller: 'categoryCtrl',   
    resolve: {
        categories: function(cartService){
            return cartService.getCategories();
        }
      }
  });
  
});

app.controller('categoryCtrl', function (categories, $scope) {
  $scope.items = categories;
});

app.service("cartService", function() {
   this.getCategories = function() {
     return ['A', 'B', 'C'];
   };
});
<html ng-app="app">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a5b545d4f565b481450497a0b140e1403">[email protected]</a>" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74151a130118150659061b01001134455a405a46">[email protected]</a>" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular-route.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="indexCtrl">
    <h1>{{title}}</h1>
     <div ng-view></div>
  </body>

</html>

Answer №2

It is necessary to specify the categories service or factory that has been included in your controller named 'ctrl'.

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

What steps can be taken to avoid the appearance of the JavaScript prompt "Leaving site"?

Hi there, I'm currently trying to find a way to remove the Javascript prompt/confirm message that asks "Do you want to leave this site?" like shown in this link: The issue I am facing is that when a modal opens and the user clicks on "YES", it redire ...

Antialiasing in Three.js is failing to work properly on Google Chrome

When using Chrome v31, I've noticed that antialiasing doesn't seem to be working properly. There are no errors in either browser. Here is the possibly relevant code: var renderer = new THREE.WebGLRenderer( { antialias: true } ); The rendering ...

Rotating the camera in first person perspective using Three.js

After struggling to find updated help on first player rotation in three.js, I am facing a challenge where most of the solutions provided are using functions that no longer exist in the current library version. I am attempting to implement a feature where ...

Only displaying the VUE slot when the content meets a certain criteria

I have encountered a situation where I have two routes rendering the same component but with different data from an API source. The component in question has a child component called <base-section> that utilizes a v-if directive to determine whether ...

Loop through the mongoose object using EJS

When I insert <%= products %> into my view, it displays [Object Object], indicating that the mongoose resultset is an object. However, when I attempt to iterate over the products object, I receive an error stating products.forEach is not a function. ...

"Utilizing Javascript to create a matrix from a pair of object arrays

Attempting to transform an infinite number of arrays of objects into a matrix. height: [1,3,4,5,6,7] weight: [23,30,40,50,90,100] to 1 23 1 30 1 40 1 50 ... 3 23 3 30 3 40 ... Essentially mapping out all possible combinations into a matrix I experime ...

"Error 404: The file you are looking for cannot be found on [custom company domain]. Please check

My attempts to retrieve a Google Drive file using its file ID with a service account in NodeJS have been unsuccessful. The requests are failing with an error indicating a lack of access: code: 404, errors: [ { message: 'File not found: X ...

I need help accessing data from a REST API and displaying it in a table

How can I call all the data in "md" and display it in a table? I've tried multiple values but none seem to work. Can someone guide me on how to use the "md" value to display in a table? <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

Executing a component's function from a JavaScript file

Is it possible in React to call a function or method of a component from a separate JS file in order to modify the component's state? Here are three example files: First, App.js import React,{Component} from 'react'; import Login from &ap ...

Using jQuery to eliminate selected item from a list

I have a basic list in html/jquery that allows users to add items. I am trying to create functionality where a specific item can be removed from the list when clicked on. However, the code for removing the item is not working as expected. Remove Item Code ...

Caution: flattenKids(): Two children with identical keys, `false`, have been detected in the ReactJS environment

Currently, I am working on creating a clickable list where each item redirects me to another page upon clicking. Below is the render method: render() { const quesItems = this.state.questions.map((question, i) => { return ( <li key={this.prop ...

NodeJS is capable of handling a limited number of requests at a time

Utilizing jQuery to send requests to a local server has been causing some issues. After sending approximately 4-7 requests, the port stops working without any visible error. Eventually, after a few minutes, some of the requests are successfully sent to the ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

Issue with Access-Control-Allow-Origin header encountered while interacting with Reddit's JSON API

Currently working on a React app that fetches data from the reddit JSON api. During development, I used the cors-anywhere demo assuming that CORS errors wouldn't appear in production. After researching CORS errors, I learned that they occur because t ...

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Video margins within a webview

After numerous attempts to embed a YouTube video in a WebView, I'm still struggling with a persistent small margin on the right side of the video. I've researched similar issues and attempted to address it through JavaScript adjustments without ...

A guide on declaring an Angular variable within a Blade template

I'm working on the following code snippet: <div ng-repeat='item in reddit.items'> and I want to assign an item attribute (@{{item.content}}) to Blade if certain conditions are met. @if(Auth::check() && !$this->ifFav(Auth::user()- ...

Incrementally add a new object to an existing array of objects

I have an array of objects below. When I do a console.log, this is what I see: [Object, Object, Object] 0:Object name: "Rick" Contact: "Yes" 1:Object name:"Anjie" Contact:"No" 2:Object name:"dillan" Contact:"Maybe" Now, I wa ...

I am in search of a JavaScript or jQuery plugin for an HTML slider with a unique range functionality

I've been searching online but couldn't find a slider like the one shown in the attachment. Can anyone help? Is there a way to create this specific slider or is there an existing plugin or library for it? Please refer to the image below :https:/ ...

Can you help me convert this Mongoose code to use promises?

Using Mongoose's built-in promise support, I aim to streamline the process of a user sending a friend request to another user. However, even with careful error handling and sequencing in place, I find myself grappling with a slightly condensed pyramid ...