Angular JS: Passing Parameters

I am a beginner in Angular and JavaScript in general. While working on building a prototype app using examples and tutorials, I have encountered a simple issue that involves passing parameters.

My goal is to receive a parameter (myKey) in my controller and pass it to a factory which will then use it for a web API request. I have tried using a constant for myKey in the factory, but I'm struggling with passing it as a parameter.

I apologize for the basic question and acknowledge that I have more studying to do.

Thank you

'use strict';

/* Factories */

angular.module("myApp.myViewer.factories", []).factory('myThings', ['$resource',
      function ($resource) {
          var resource = $resource('/api/myThings', {}, { get: { method: 'GET', params: { myKey:"M1234" } } });

        return resource;
    }
]);


/* Controllers */

angular.module("myApp.myViewer.controllers", [])
   .controller('myCtrl', ['$scope', 'myThings', function ($scope, myThings) {

      myThings.get(function (response) {
          console.log(response);
          $scope.myThing = response;
      });
  }]);

Answer №1

These two modules are independent of each other and do not have any knowledge about one another. To establish a connection between them, you must specify one module as a dependency of the other using the following approach:

angular.module("myApp.myViewer.controllers", ["myApp.myViewer.factories"])

However, I believe that this might overcomplicate matters in this scenario. It would be beneficial to merge both modules together like so:

In addition, it is necessary to include ngResource as a dependency and confirm that it is properly loaded on your pages since Angular does not come bundled with it.

angular
  .module("myApp", ['ngResource'])
  .factory('myThings', ['$resource', function ($resource) {

        return {

          // Define a function that returns your $resource after
          // passing the 'myKey' parameter
          resource: function(myKey){
            return $resource('/api/myThings', {}, { 
              get: { 
                method: 'GET', 
                params: { myKey: myKey }
              } 
            });
          }

        };

      }

  ])
  .controller('myCtrl', ['$scope', 'myThings', function ($scope, myThings) {

      // Inject the myThings service and utilize the resource function
      // defined earlier to create your resource object.
      var Keys = myThings.resource(myKey)

      // Perform a get request on your resource and
      // assign the response value to a $scope variable
      // enabling properties from the response object to be displayed in 
      // the view template
      Keys.get(function (response) {
          console.log(response);
          $scope.myThing = response;
      });
  }]);

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 causes the variable initialized in ng-init to be undefined within the $scope in AngularJS?

I am facing an issue with accessing a variable in my controller that I set in my view using ng-init. Despite setting the variable, I am getting an undefined error when I try to access it. Below are the relevant code snippets: View: <div ng-controller ...

Streamline the entire testing process of Google.Com by using Protractor to automate end-to-end testing

I need help with making Protractor navigate to google.com and search for a term. After successfully loading the non-angular page of Google, I am struggling to figure out how to make Protractor press "enter" or click the search button. Any suggestions? Ad ...

Establishing the Access-Control-Allow-Origin

I have a basic .NET web service: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; /// <summary> /// Summary description for WebService /// </summary> [WebService(Namespace = "http ...

The pause and restart buttons are malfunctioning and are not functional

My goal is to create a stopwatch using JavaScript that can start and stop the timer. I want to store the time data in my MySQL database when the user presses the stop button. However, I am facing issues with the pause buttons not functioning properly. f ...

Send key-value pairs to the function using ng-model

I am currently working on a functionality that involves extracting an object from json and displaying its key-value pairs using 'ng-repeat' in AngularJS. The form includes checkboxes where the value can be either true or false, determining if the ...

Even though assets are precompiled, the application is still searching for each individual JS file

My Capistrano successfully precompiles all assets in the pipeline and generates the application.js and application.css files. However, my application is still searching for separate .js and .css files that are not on the server, resulting in numerous 404 n ...

VueJS error: Trying to access properties of undefined object ('$refs') is unsuccessful

Parent Component: ... <v-stepper-step :rules="[()=>isValid(1)]" > MyStep </v-stepper-step> <v-stepper-content> <Mytag ref="MyReference" /> </v-stepper-content> ... methods: { isValid(number){ ...

There seems to be an error in the month within the

Can anyone explain why the month increases by 1 if its value is higher than 9? See the code snippet below: var dd = new Date(); dd.setFullYear(2017); dd.setMonth(7); console.log("Month(Expected: 7, Received: " + dd.getMonth() + ")"); dd.setMonth(10); cons ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

Swiper V7 React is experiencing issues with numerous parameters not functioning properly

Here is the code snippet I have been working on: I am currently exploring the Swiper library documentation to understand its functionalities better. import React from "react"; // Direct React component imports import { Swiper, SwiperSlide } fro ...

Endless rotation with stunning magnification feature

My goal is to create a responsive carousel with auto-play infinite loop functionality, where the center item always occupies 70% of the viewport width. Currently, I have achieved a similar result using the Slick library: https://codepen.io/anon/pen/pBvQB ...

Discover the dimensions of the viewport using jQuery

I am currently attempting to use jQuery to determine the size of the viewport, but I am not achieving the desired results. Here is my CSS code: .site { max-width: 960px; } @media only screen and (min-width : 760px) and (max-width : 1040px) /* table ...

The initial data fails to load with ng-model

My project involves creating an application that calculates the volume of furniture pieces. I need to bind the height, width, and depth to input elements within a form. Here is an example: <input class="form-control" type="number" name="input" ...

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

Determine whether the browser tab is currently active or if the user has switched to a different

Is there a way to detect when a user switches to another browser tab? This is what I currently have implemented: $(window).on("blur focus", function (e) { var prevType = $(this).data("prevType"); if (prevType != e.type) { // handle double fir ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Animate a div component sliding out while seamlessly introducing a new one using React

For my signin page, I've set it up so that users first enter their username and then click next to trigger a fluid slide animation which reveals the password field from the right. Although the separate components are already coded and the animation wo ...

The functionality of AngularJS ng-pattern does not behave as anticipated when used with specific conditions

I have been attempting to use conditions with ng-pattern, but it constantly shows the zip code as invalid. If I remove the condition and just use the pattern, everything works fine. <md-input-container flex="20"> <label>Zip Code ...

Tips for using the useState hook to modify an array by its index?

I am working on a select component that needs to update values in an array of objects based on the index. Utilizing the hook as follows: const [areas, setAreas] = useState(product.areas); This is how the "areas" array looks: [ 0: {de: "Getraenke", en: ...

Error: The property 'map' is not defined in my application, causing a TypeError

I'm encountering an issue every time I attempt to iterate over an ingredients array Below is the list of ingredients ingredients": [ "2 jalapeno peppers, cut in half lengthwise and seeded", "2 slices sour dough bread", "1 tablespoon butter, ro ...