Developing object instances using AngularJS

Looking for some guidance on creating an object using Angular's factory capabilities since I'm new to AngularJS. Here's the code snippet that I have:

angular.module('7minWorkout')
.factory('WorkoutPlan', function(args){
      this.exercises = [];
      this.name = args.name;
      this.title = args.title;
      this.restBetweenExercise = args.restBetweenExercise;
      this.totalWorkoutDuration = function () {
          if (this.exercises.length == 0) return 0;
          var total = 0;
          angular.forEach(this.exercises, function (exercise) {
              total = total + exercise.duration;
          });
          return this.restBetweenExercise * (this.exercises.length - 1) + total;
      }
     return this;
  }); 

Upon running this, I encountered the following error message:

Error: [$injector:unpr] Unknown provider: argsProvider <- args <- WorkoutPlan

Any insights on what might be causing this issue?

Appreciate any help!

Answer №1

A common issue arises when the args argument is not a valid injectable module such as $scope or $http.

To solve this problem, consider defining your class internally and returning a new instance of it. Take a look at an example below:

angular.module('myApp')
.factory('CustomClass', function() {

  var myCustomClass = function(args) {
    this.properties = [];
    this.name = args.name;
    this.description = args.description;
    this.method = args.method;
    this.totalDuration = function() {
      if (this.properties.length == 0) return 0;
      var total = 0;
      angular.forEach(this.properties, function(property) {
        total = total + property.value;
      });
      return this.method * (this.properties.length - 1) + total;
    }
  };

  return {
    create: function(args) {
      return new myCustomClass(args);
    }
  };
});

To use this factory, simply inject CustomClass into the controller or directive, then call CustomClass.create(newArgs); to create an instance.

Answer №2

To properly utilize your factory in Angular, you must specify that it requires a parameter by following this format:

angular.module('7minWorkout')
    .factory('WorkoutPlan', ['args', function(args){
        this.exercises = [];
        this.name = args.name;
        this.title = args.title;
        this.restBetweenExercise = args.restBetweenExercise;
        this.totalWorkoutDuration = function () {
            if (this.exercises.length == 0) return 0;
                var total = 0;
                angular.forEach(this.exercises, function (exercise) {
                total = total + exercise.duration;
            });
        return this.restBetweenExercise * (this.exercises.length - 1) + total;
    }
    return this;
}]); 

If you don't declare the parameter, Angular will interpret args as a provider being injected into your factory, leading to errors. Refer to this resource for more information (specifically the Factory Recipe section).

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 is the best method for expanding the width of a <rect> element with animateTransform?

How can I make a <rect> in SVG expand its width using animateTransform based on a specified value? Additionally, I want the color of the <rect> to change according to the following conditions: If the <rect> value is between 0 and 29: {f ...

Is there a way retrieve all named HTML tags and store them in an array?

In need of assistance with parsing data from a page that is formatted as follows: <tag>dataIwant</tag> <tag>dataIwant</tag> <tag>dataIwant</tag> <othertag>moarData</othertag> <othertag>moarData</oth ...

Having trouble with JavaScript in a project I'm trying to replicate

For my coding practice, I am working on a project where clicking on the images should change the main product displayed along with its color. However, nothing happens when I click on the products. Can anyone point out what I might be doing wrong? Here is ...

Windows location does not change after an XMLHttpRequest is made

Here is my code that uses XMLHttpRequest: function SignUp() { signUpConnection = new XMLHttpRequest(); signUpConnection.onreadystatechange = processRegistration; signUpConnection.open('GET', 'index.php?registrarse=&username= ...

Using controllerAs in an AngularJS directive allows for multiple instances to be created, each with the

In my form, I have directives that contain identical input fields, selects, and check boxes. To handle this, I created a directive with an isolate scope and controllerAs syntax using bindToController=true. The controller has a method triggered by an ngChan ...

How to Show a GIF in ASP.NET Core 3.0 When OnPost() is Invoked

I'm struggling to incorporate a GIF into my website, and after researching different sources, I've discovered that I need to utilize some Ajax and Javascript. However, I lack experience with both of these technologies. Is there anyone who could p ...

JavaScript form validation involves using client-side scripting to ensure that

I'm currently working on form validation, but I'm unsure if I'm overcomplicating things. I have a variable that compares elements and replaces an image with a checkmark for success or an X for failure upon successful validation. The function ...

Tips on altering the color of a circle's radius within Google Maps

I'm trying to add a circular radius on a Google Map. Even after reviewing the Google Maps API documentation, I'm still unsure of how to accomplish this task. Below is the code snippet I have been working with: const MyMapComponent = compose( ...

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

"The event triggers the function with an incorrect parameter, leading to the execution of the function with

Currently, I am working with a map and a corresponding table. The table displays various communities, each of which has a polygon displayed on the map. My goal is to have the polygons highlighted on the map when hovering over a specific element in the tabl ...

Having trouble with the `npm start` command while working with react.js?

Currently, I am in the process of setting up React.js. To achieve this, I executed npm install -g create-react-app followed by create-react-app my-app. Afterward, I proceeded to run the npm start command but encountered the error displayed below. https:// ...

Tips for utilizing a shared controller in an Angular Material popup dialogue

Within my project, Angular Material is being used for various dialogs, primarily for alert purposes. However, I now find myself in need of a more complex dialog. The example provided on the Angular Material site showcases how to create a dialog: function ...

Having trouble accessing variables using the put method in Laravel with XMLHttpRequest

I am struggling to save my image data using XMLHttpRequest. Although I can send json data and see them in the developer console, I am unable to access them on the server side as the $request appears to be null. Below are snippets of my JavaScript code: ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

Ensuring Accessibility in Vue using Jest-Axe: It is important for buttons to have clear and distinguishable text. Is there a way to include a button name or aria-label when the content is passed through a slot

I have been focusing on enhancing the accessibility of my project by incorporating ESLint rules from vuejs-accessibility and integrating Jest-Axe. During the accessibility tests for my button components, Jest-Axe highlighted that Buttons must have discern ...

Refreshing JWT Authentication in Angular

I am currently following a tutorial on Egghead.io, which can be found here. However, I am adding a MongoDB to fetch my users which is causing me some issues. I have managed to get everything working except for the part where it mentions that the /me route ...

Endless Loop Seamless Vertical JavaScript Experience

I've been working with an HTML table structure of data and was successful in setting up a vertical list loop using some JavaScript. However, I'm facing challenges in achieving a smooth constant vertical scroll. Currently, it goes row by row when ...

A guide on incorporating a method using ES6 Rest into a JavaScript object

My goal is to enhance my Person constructor by adding a method that allows users to add friends. I wanted to utilize the "rest" feature of ES6 to pass a variable number of friends, but I seem to be stuck. My initial attempt resulted in an error ("Uncaught ...

Using JavaScript to manipulate an HTML canvas

I currently have an index.hTML file that is set up to display a canvas using the following code: <body> <canvas> </canvas> <script src="./JS/index.js" type="module"></script> </body> Within my JavaScript fi ...

Tying a progress bar to the data being loaded in Angular JS

I am currently utilizing the bootstrap-ui progressbar along with AngularJS $http for an AJAX request. The task at hand involves syncing the progress bar with the data received by Angular during the request process. To elaborate, if the server is expected ...