Creating a factory in AngularJS: A step-by-step guide

I set up a factory in Angular, but I'm encountering the following error message:

Unknown provider: 

This is how the factory looks:

app.factory("getFoo", function($scope){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
     } 
});

And here is the controller:

app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);
}])

I don't understand what's causing this issue. Can you help me identify and fix it?

Answer №1

no requirement for scope, update your factory injection as shown below

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

app.controller('MainCtrl', function($scope, getFoo) {
   $scope.myArr = getFoo.getCommi(4,1);
  
});

app.factory('getFoo', function () {
  return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
     } 
});    
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9c939a88919c8fd3978ebdccd3cfd385">[email protected]</a>" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>{{myArr}}!</p>
  </body>

</html>

Answer №3

Kindly eliminate the usage of $scope in the factory.

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

app.factory("getFoo", function(){
    return {
       getCommi: function(val,id){
          var array = ["hello","world"];
          return array;
       }
    } 
});

app.controller('myCtrl', ['$scope','getFoo',function($scope,getFoo){
   $scope.myArr = getFoo.getCommi(4,1);

}])

Answer №4

To enhance your factory, you should consider eliminating $scope and introducing the factory "getFoo" as a dependency in the run module of your application as demonstrated below:

app.run(['$rootScope', '$location', 'getFoo', function($rootScope, $location, getFoo) {

}]);

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

I'm experiencing a roadblock due to ng-submit not functioning as expected, failing to execute when clicked

I'm currently enrolled in an online course and I've hit a roadblock with one of my assignments. The assignment involves a form with a submit button that triggers certain code upon clicking. However, when I click the submit button, the code doesn& ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

How can I change the "Return" button on the iOS keyboard to a "Next" button using jQuery or JavaScript?

Currently, I am developing an HTML application and working on implementing it for IOS devices such as the IPAD. Within my application, there are multiple text boxes. Whenever a user clicks on a text box to input text, the keypad appears. On this keypad, ...

Having difficulty adjusting the width of a div element

I've been struggling to adjust the width of the div assigned with the colors class, whether in percentage or pixels. var colors = ["RED", "GREEN", "BLUE", "YELLOW", "PURPLE"]; for (var h = 0; h <= 4; h++) { for (var i = 0; i <= colors.lengt ...

Guide to dynamically adding a class in VueJS based on a certain condition

I'm in the process of transitioning a project to Vue, and I'm curious about how I can dynamically assign classes to specific elements based on database values rendered with Vue. Previously, I had this code set up without Vue: $(document).ready(f ...

Storing information in local storage as JSON using AngularJS

I am working on a form with the following fields: <form ng-submit="addState()"> <input ng-model="text1" type="text"> <input ng-model="text2" type="text"> <input ng-model="text3" type="text"> ...

Disappearance of icon upon hovering in CSS

I am currently working with Angular JS (1.x) and I have a requirement to display tooltip text when hovering over an info icon. The tooltip text appears properly, but the issue is that the icon disappears when hovered over. It reappears once the hover is re ...

Issues arise when using res.send() with ExpressJS and Mongoose

Initially, I have multiple callbacks that need to be executed before sending a res.send() to construct a JSON API: app.get('/api', function (req, res){ ... function logPagesId() { console.log("load: " +pagesId); c ...

Setting up instagram-node-lib for managing subscriptions

I am currently working on implementing real-time updates for a specific hashtag and displaying the image on the screen. However, I am facing issues setting up my node.js server using the instagram-node-lib module. Even after running the file (node server.j ...

What is the purpose of using CORS with Express?

Here is how my express server setup looks: const cors = require('cors'); const express = require('express'); const app = express(); const port = 8000; app.use(cors({origin: 'http://localhost:8000'})); // Handle requests of c ...

Set up specific vue.config.js configurations for unique environments in Vue

I am working on a multi-page app where I want certain pages to only show up in my development environment. Here's how my vue.config.js looks: module.exports = { productionSourceMap: false, pages: { index: "src/main.js", admin: { ...

Is it possible for an object filter to allow the object to pass through without a designated name?

In the javascript code below, I have managed to achieve the desired outcome by returning the 3rd and 4th objects in objectsArray since they both have the maximum distance. However, I am curious if there is a way to avoid repeating the name of the array whe ...

Changing CSS class on button click in React.js app

Is there a way to add a blur effect to my background when a user clicks a specific button? I want to update my CSS class accordingly. Below is the current CSS class: .post_options { width: 100%; height: 100%; float: left; background-color ...

How can I forward a post request to a different URL in a node.js application?

I am attempting to forward a POST request from one server to another server while including additional parameters from the initial request. Take a look at the code snippet below. app.use(bodyParser.urlencoded({ extended: true })); app.post('/pay1&ap ...

Sequelize transforms any given date object into a local date representation

When running a query with a data replacement, the date is not set as UTC in the query. Here's the code snippet: let startInterval = moment('2020-12-09').toDate(); db.query(` SELECT kv.kpiId FROM kpiValues kv WHERE kv.insertDate ...

Issues with navigating sliders

I've encountered a problem with my slider arrows while following a YouTube tutorial. They are supposed to appear next to the picture and testimonial, but instead, they are showing up at the top. This issue wasn't present initially, but after enco ...

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...

How can I achieve a fade-in effect whenever the flag image is clicked?

A unique "international" quotes script has been created, showcasing Dutch, English, German, and French quotes. The script displays different quotes every day, with a draft-result visible in the upper right corner of this page ... The code used for this sc ...

Dealing with the output from the response.write() function in Express within an Angular $http request

Currently, I am attempting to upload a CSV file using the ng-file-upload library. Below is a snippet of my code: Upload.upload({ url: baseUrl + '/file-upload', data: { file: file } }) .then(function(res) { console.log(' ...

How come props do not get updated along with state changes?

I've encountered an issue where the state of a component being passed into another component as a prop is not updating correspondingly. Various attempts have been made to resolve this, including placing it in the return function and updating the "low ...