Angular keeps throwing an error saying "Provider not found" when trying to inject a factory

Issue:

Encountering an Unknown Provider Error in Angular App for: UnitProvider <- Unit

Error Details:

Error: [$injector:unpr] Unknown provider: UnitProvider <- Unit

Codepen Link:

View LIVE CODE Example


I recently came across a fascinating video about Angular on YouTube titled:

Crafting the Perfect AngularJS Model and Making it Real Time

Find more info on Github: Repo


Insight:

Feeling motivated after watching the video, I believe I grasp the concept and outcome of this method, but I'm struggling to connect all the dots. Any additional comments or explanations would greatly assist me!

Code:

JavaScript Code:

angular.module('Modelbuildr', []).config(function() {});
var app = angular.module('Modelbuildr');

app.controller("MainCtrl", function($scope, Unit)           
{
  $scope.name = "world";
  $scope.units = Unit;
  var vecA = [1,2,3,4,5];

    $scope.vecB = _.map(vecA, function(num){
      return num * 2;
    });
});

function Resource($http, path) {
    _.extend(this, {
      _http: $http,
      _path: path
    });
}

Resource.$factory =  ['$http', function($http) {
    return function(path) {
      return new Resource($http, path);
    };
}];

app.factory('bdResource', Resource.$factory);

Resource.prototype.find = function(uid) {
    var deferred = Q.defer();

    this._http.get(this.path(uid))
      .success(deferred.resolve)
      .error(deferred.reject);

    return deferred.promise;
};

Resource.prototype.path = function(uid) {
    return uid ? this._path + '/' + uid : this._path;
};

Resource.prototype.set = function(uid, newValue) {
    var deferred = Q.defer();
    var path = this._path + '/' + uid;

    this._http
      .put(path, newValue)
      .success(deferred.resolve)
      .error(deferred.reject);

    return deferred.promise;
};


function Unit(futureUnitData) {

    if (!futureUnitData.inspect) {
      _.extend(this, futureUnitData);
      return;
    }

    this.$unwrap(futureUnitData);
}

Unit.$factory = ['$timeout', 'bdResource', function($timeout, Resource) {
    _.extend(Unit, {
      $$resource: new Resource('/units'),
      $timeout: $timeout
    });

    return Unit;
}];

angular.module('Modelbuildr').factory('bdUnit', Unit.$factory);

Unit.$find = function(uid) {

    var futureUnitData = this.$$resource.find(uid);

    if (uid) return new Unit(futureUnitData);

    return Unit.$unwrapCollection(futureUnitData);
};

Unit.prototype.$unwrap = function(futureUnitData) {
    var self = this;

...

**HTML Code:**

<body ng-app="Modelbuildr" ng-controller="MainCtrl">
  <h1>Empty Angular App</h1>
  Hello {{name}}.
  Lo-dash {{vecB}}.
</body>

Answer №1

When incorporating the Unit into angular's module, it is defined as bdUnit:

angular.module('Modelbuildr').factory('bdUnit', Unit.$factory);

Therefore, when utilizing it, make sure to do so in the following manner:

app.controller("MainCtrl", function($scope, bdUnit) { .. });

Alternatively, you can explicitly instruct angular to rename bdUnit as Unit:

app.controller("MainCtrl", ['$scope', 'bdUnit', function($scope, Unit) {
  ..
}]);

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

Inquiring about the intricacies of using Regular Expressions in

Can anyone provide a regex that only allows the characters 0-9, a-z, A-Z, hyphen, question mark, and "/" slash, with a character length between 5 to 15? I attempted the following approach, but it did not yield the desired result: var reg3 = /^([a-zA-Z0-9? ...

Traversing through Object consisting of dual arrays within VueJS

Currently, I am working on a chat application built in VueJS and encountering an issue when attempting to display messages along with their respective timestamps. The challenge arises from the need to iterate through an object that contains two arrays: one ...

Express.js: Defining a base route can cause issues with resolving static files

I'm currently working on a project using express.js and react.js, but I've encountered some issues that I can't seem to find solutions for. I have set up a base directory where the express server is located, and within that, there's a ...

Objects and strings cannot be inserted into a JavaScript array

For hours, I've been attempting to troubleshoot this code. Currently, it successfully finds the number of anchors, and I have an array that is of undetermined size. Within the for loop, it retrieves the anchor and extracts the .href. I've confirm ...

Dynamic script appending encounters unforeseen challenges

After attempting to add a script either on click or after a time delay, I am encountering an issue where the script is not being appended. Strangely, if I remove the setTimeout function, the script gets added successfully. The same problem persists with ...

get selection choice from the server

I have been trying to update my option select menu when the button is clicked without clearing out the menu. Currently, I am using $(#id).click(function(){}); but it seems that this approach is causing the select menu to clear out. Upon further investigati ...

What could be causing the issue with this jQuery selector for the parent form element?

I created a form that connects a button with an attribute, but it's not hiding the parent("form"). However, when I try this, it works. $($("[editFormContent]").attr("editFormContent")).click(function(e) { e.preventDe ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

How can I display a nested dropdown list within a form using JSON data in React?

Utilizing material ui and formik, I have integrated a form that requires a selection box with nested options to be displayed as shown in the image linked here. (The value selected needs to be submitted upon form submission) To keep it simple: I am aiming ...

How can you incorporate a value into a variable in PHP?

Hey there! I'm pretty new to PHP and I've been working on building a program that resembles a spreadsheet. My form consists of columns and cells, allowing users to add or delete rows using Javascript. The challenge I'm facing is automating t ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

What are the possibilities of utilizing a variable that is stated within composition to enable dynamic rendering?

I'm working on a Vue.js v3 project using the composition API. I have defined a variable in my setup like this: setup() { const showInvoiceItemForm = true; return { showInvoiceItemForm }; }, Now, I want to show a form when a button is click ...

`I'm having issues trying to use ajax and load simultaneously``

Can anyone help me figure out why my AJAX call to sessions.php is not correctly loading and returning true or false each time a user accesses the page? var section = $("#header a"); section.on('click', function() { $.ajax({ type: "PO ...

Tips on incorporating a URL from a text file into a string

Could anyone assist me in adding a URL text file containing just one sentence and saving it as a string? Your help would be greatly appreciated. Thank you. ...

Implementing efficient loading and dynamic updates in web applications with Angular.js and php through

Currently, I am working on a project that requires lazy loading of images. However, a new requirement has come up which involves a server batch process pulling images from a database at regular intervals. These images must then be appended to the photos ...

I am encountering an issue while trying to update SQL data from within a Node.js

Using a for-loop to update SQL command is common practice. Here's an example: for(var i=count1; i < count2;i++){ Book.TimeStart = Times[I] console.log(Book.TimeStart) sql = sql + `UPDATE projectroom.Details SET BookingId = `+Book.Bo ...

Testing the change in states with resolve functions in AngularJS

Testing in AngularJS is still new to me, and I'm currently working on writing tests for a $stateProvider that I've set up like this: angular.module("app.routing.config", []).config(function($stateProvider, $urlRouterProvider) { $stateProvider. ...

Retrieve the place_id associated with the address components

Having trouble obtaining the place_id of address_components using Google place autocomplete? The JSON data only includes long_name, short_name, and types. Take a look at my code snippet below: var object_location = document.getElementById('object_loc ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

Guide on merging two JSON objects in AngularJS

In my angular controller, I have the following code: var jsonOne = $cookies.get('test'); // console logs {"domain":"localhost","zip":33333} var jsonTwo = angular.toJson($scope.formData); // console logs {"id":"210","name":"sam"} var final = $. ...