Error encountered while using parameters in Angular service

I have been struggling to pass two variables from an angular service to an MVC controller, but I keep encountering errors. The latest error I'm getting is that 'compName' doesn't exist. I've spent hours trying to debug the issue using the Angular debugger, but so far, no luck.

        myApp.service('getDocTypesService', ['$http', '$q', function ($http, $q) {
        var allSettings = null;
        this.getDocTypes = function (compName, custName) {
            var def = $q.defer()
            if (allSettings) {
                def.resolve(allSettings);
            } else {
                $http.post('GetDocTypes', { companyName: compName, customerName: custName })
                  .then(function (response) {
                      var response = $.parseJSON(response.data)
                      allSettings = response;
                      def.resolve(allSettings);
                  });
            }
            return def.promise;
        }
        }]);

I believe the issue may be related to the fact that the angular controller is attempting to call the service on load rather than on click. However, I'm not sure how to address that.

This is the code for my angular controller and service:

      myApp.controller('myController', ['$scope', 'getDocTypesService',
      function ($scope, getDocTypesService) {
      $scope.docSettings = '';
          getDocTypesService.getDocTypes(compName, custName).then(function (value) {
          $scope.docSettings = value

          })

          };
      }
      ]);

Here's the HTML snippet:


    <select ng-model = "selectedDocument" ng-click="getDocTypes(selectedCompany, enteredCustomer)">
    <option>Select document</option>
    <option ng-repeat="docSetting in docSettings" value=" {{docSetting.Doc_Type}}">{{docSetting.Doc_Type}}</option>
    </select>

Answer №1

Give this a shot:

controller:

$scope.retrieveTypes = function(company, customer) {
    docTypeService.getDocumentTypes(company, customer).then(function (data) {
          $scope.docConfig = data;
    });
};

Template:

<select ng-model="selectedDocument" ng-click="retrieveTypes(selectedCompany, enteredCustomer)">

Note: Make sure that selectedCompany and enteredCustomer are $scope variables defined prior to the click event.

Answer №2

It seems that you are passing a parameter through a function that does not exist. You will need to define the following function:

$scope.getDocTypes = function(selectedCompany, enteredCustomer) {
  getDocTypesService.getDocTypes(selectedCompany, enteredCustomer).then(function(value) {
    $scope.docSettings = value;
  });
}

Answer №3

.provider('MagReviews', function ($http) { return $http.get('http://example.com/api/magReview/:id', { username : userEntity, password : userPassword, id : '@reviewId' }); })

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 way to establish the render() method for an 'arrow' component?

I came across the following code snippet: const CoolComponent = props => { ... I am looking to add a render() function to it: render() { console.log('Hello world'); return ( <Bar foo={true} {...propz} ...

If a submit event listener was added to the form, what will the event.target contain?

I am managing multiple forms on a single page, and upon submission of one form, I aim to send an AJAX request with specific data to the backend view. My goal is to identify if the clicked form matches the event target in order to proceed. I attempted the f ...

Issues with implementing jQuery on Crispy Forms input fields are causing unexpected behavior

<div id="div_id_code" class="form-group"> <label for="id_code" class="control-label col-lg-2 requiredField"> Code<span class="asteriskField">*</span> </label> <div class="controls "> <input type="text" ...

Tips for optimizing the use of JS promises?

I'm encountering issues with implementing promises in JavaScript. There are 3 asynchronous functions that rely on each other: The functions are named func1, func2, and func3 respectively. func1 produces a single result that func2 requires. func2 a ...

Angular: Design dependent on attributes

Can I customize the styling of a div in accordance with a boolean property called "isActive" on my controller using Angular? <div class="col-md-3" (click)="isActive = !isActive"> <div class="center"> <i class="fa fa-calendar"& ...

Comparing the efficiency of using arrays versus mapping to an object and accessing data in JavaScript

When considering the basics of computer science, it is understood that searching an unsorted list typically occurs in O(n) time, while direct access to an element in an array happens in O(1) time for HashMaps. So, which approach yields better performance: ...

Angular directives for Kendo UI

I have been working with Angular 1.5.* in conjunction with Kendo UI. I have followed all the steps outlined in the documentation on the Telerik site, including: Ensuring that the kendo scripts and styles are included Adding kendo.directives to my angular ...

Retrieve a specific value from an array within Firestore

I am facing an issue where I can only retrieve the values I need from the array by adding a specific string like "اقلام" or "سبورة". However, I want the value to be passed as a prop from another component or screen. Is there a way to resolve this ...

Deselecting a radio button using AngularJS

I currently have three radio buttons like this: <input type="radio" name="project" data-ng-model="vm.defaultProject" data-ng-value="projectUserConnection.project" /> If I select one of the radio buttons, I am unable to deselect it unless I select a ...

Retrieve external URL from backend and perform a redirection after clicking on the <p:button> element

I have a task that I am working on where I need to display a button. The target URL for this button is obtained by making a SOAP request to an external third party (Single Sign In) which provides the sign-in URL. I want to ensure that my page's load t ...

What is the process for invoking a window function in a universal React application?

When working with an Isomorphic react application, we utilize the same codebase for both client and server. However, one common issue is how to call a window.function() from inside a server-side (Node.js) call. Attempting to call a function in a third-par ...

What is the method for retrieving the current value of a BehaviorSubject just once?

I am attempting to retrieve the current value of a BehaviorSubject without directly subscribing to it in order to avoid real-time changes reflecting immediately due to a specific requirement. My approach involves using the getValue() method. Here is an ex ...

What could be the reason for Object.assign failing to update a key in my new object?

Function handleSave @bind private handleSave() { const { coin, balance } = this.state; console.log('coin', coin); console.log('balance', balance); const updatedCoin = Object.assign({ ...coin, position: balance }, coi ...

What are some creative ways to design the selected tab?

In my Vue parent component, I have multiple child components. There are several elements that toggle between components by updating the current data. The issue is that I am unsure how to indicate which tab is currently active. I've tried various li ...

Error encountered: Attempting to use a class as a function in vue-socket.io is not permitted

I am developing a Vue chrome extension where I am attempting to implement web sockets using vue-socket.io. I have followed the basic instructions on deploying a node server with express and socket.io on Heroku, but I am encountering issues with the conne ...

Updating the InitialRouteStack within the React Native Navigator component

I am currently facing an issue with my Navigator component. It needs to handle 4 different views that should all be on the same level. I have set them in the InitialRouteStack and navigate between them using jumpTo(route) as needed. However, when a value ...

Visualization with D3 - Putting an image at the heart of a circular chart made with SVG

Is it possible to add an image to the center of a donut SVG in D3 charts using JavaScript? I've been attempting to achieve this but haven't had any success so far. Currently, I have inserted the image in HTML, but it does not align with the cent ...

Acquiring HTML form data using JavaScript

Although it may seem trivial, I'm facing a challenge. I have an HTML form that is dynamically generated by JavaScript and populated with initial data fetched from the server. The form is displayed correctly with the pre-filled data. My goal is to allo ...

Is it necessary for consumers to import global augmentations as a side effect?

I created a package named core.error which consists of two files: global.d.ts export {}; declare global { export interface Error { foo(): void; } } index.ts Error.prototype.foo = function (this: Error): void { }; export const dooFoo = (err:Er ...

Creating a Build System for JavaScript in Sublime Text

While working on developing an application using node.js, I decided to create a JavaScript build system in Sublime Text 3 on my Ubuntu OS. I made a new build system file named nodey.sublime-build with the following contents: { "cmd": ["node","$file"," ...