How can a factory be utilized within a method defined under a $scope?

As a newcomer to AngularJS and Ionic, I am currently delving into Ionic 1. My current endeavor involves defining a function within my controller for a login view page that should only execute upon clicking the submit button. Here is the directive setup I have implemented:

<ion-view title="Login" id="page5">
  <ion-content padding="true" class="has-header">
    <h4 id="login-heading8" style="color:#000000;font-weight:400;">Please enter your phone number:</h4>
    <form ng-submit="send()" id="login-form1" class="list">
      <ion-list id="login-list1">
        <label class="item item-input" id="login-input1">
          <span class="input-label">Phone:</span>
          <input type="tel" placeholder="" ng-model="formData.phoneNumber">
        </label>
      </ion-list>
      <div class="spacer" style="height: 40px;"></div>
      <input value="Submit" type="submit" id="login-button1" style="border-radius:1px 1px 1px 1px;" class="button button-positive button-block">
    </form>
  </ion-content>
</ion-view>

My solution involves creating a new function within my $scope to prevent it from being called before the submit button is clicked. Here's a glimpse at the controller setup:

.controller('loginCtrl', ['$scope', '$stateParams', 'httpService', 
function ($scope, $stateParams, httpService) {
  $scope.formData = {phoneNumber : ""};
  $scope.send= function(httpService){
    httpService.getCall("http://localhost:8000/Hermerest/web/app_dev.php/api/parents?telephone=" + $scope.formData, loginCtrlCallback);
  }
}])

I've attempted to utilize a factory method to streamline my code and avoid redundancies. However, injecting httpService as a parameter into $scope.send() seems to be causing issues as it is recognized as undefined. Here's a snippet of my factory code:

.factory('httpService', function($http){
  return {
    getCall: function(url, callback){
      $http.get(url)
        .success(function (response) {
          alert(response);
          //callback(response);
        })
    },

    postCall: function(url, data, callback){
      $http.post(url, data)
        .success(function (response) {
          alert(response);
          //callback(response);
        })
    }
  }
})

Being relatively new to this, I am open to any suggestions or fixes that could potentially resolve this issue. Thank you in advance for your assistance!

Answer №1

There is no need to include httpService as a function parameter. It is already available in your controller because you have injected it as a dependency.

Simply use the following code:

 $scope.submit = function(){
    httpService.getCall("http://localhost:8000/Hermerest/web/app_dev.php/api/parents?telephone=" + $scope.formData, loginCtrlCallback);
  }

Answer №2

To improve efficiency, make sure to catch the promise from the controller instead of the factory. There is no necessity for using a callback since the promise will return the data directly to the controller.

Also, ensure that you return the $http from the factory.

getCall: function(url){
   return $http.get(url);
}

When working in the controller, utilize then instead of success. The latter has been deprecated since Angular 1.4.

.controller('loginCtrl', ['$scope', '$stateParams', 'httpService', 
    function ($scope, $stateParams, httpService) {
      $scope.formData = {phoneNumber : ""};
      $scope.send= function(){
        httpService.getCall("http://localhost:8000/Hermerest/web/app_dev.php/api/parents?telephone=" + $scope.formData)
         .then(function (response) {
            alert(response.data); 
          })
      }
 }])

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

Maintain a consistent header height with CSS even when using the calc() function

--dis: calc(var(--max-height) - var(--min-height)); /* @media large{--min-height:13rem}; @media small{--min-height:6.5rem}; --max-height:75vh; */ --percent: calc(var(--scroll-ani) / var(--dis)); /* in js: document.body.style = "--scroll-ani: ...

Sending AJAX information to multiple pages

I have created an HTML page where I am struggling to pass two variables using the POST method to a PHP page. The PHP page is supposed to accept these variables and then call an API to retrieve data based on them. However, my challenge is in receiving this ...

Create styles for each component based on their specific props when designing a customized Material-UI theme

I am having trouble styling the notchedOutline of a disabled <OutlinedInput /> in my custom MUI theme. My goal is to make the border color lighter than the default color when the input is disabled. Here is what I have attempted so far: const theme = ...

Socket.io-powered notification system

I'm currently in the process of developing a notification system for my Events Manager Website. Every time a user is logged in and performs an action (such as creating an event), a notification about the event creation should be sent to other user ...

Having trouble with installing sass via Gem in the Windows terminal

I am working on creating a Web Application with Angular JS and I am currently in the process of developing an Admin Panel. For this project, I will be using the Flatlogic Angular Material Dashboard template from here. To set up the admin panel, I am follow ...

Eliminating an element from an array depending on the value of its properties

I need to remove an object from my List array by matching its properties value with the event target ID. Currently, I am using findIndex method to locate the index ID that matches the event.target.id. Below is an example of one of the objects in my list a ...

Executing a javascript function from PHP when a form is submitted: a comprehensive guide

I am looking to trigger a javascript function from PHP when the form is submitted. This function will have access to PHP variables and will use AJAX to send them to a PHP script on another website. The code below serves as an example: <?php .... ..... ...

Try implementing toggleClass() in the accordion feature rather than addClass() and removeClass()

Hey there! I've implemented accordion functionality using the addClass() and removeClass() methods. Here's a breakdown of what I did: <div class="container"> <div class="functionality">Accordion</div> <ul class="acco ...

How can I utilize the context menu feature within a Material React Table row?

I am looking to implement a context menu for each row of the MUI Table, but I haven't found a suitable example. Is there native support for row-level context menus in the MUI Table, or is it possible to add this functionality per row? For reference, ...

What is the best way to alphabetically arrange an array of names in a JavaScript.map?

I am attempting to alphabetically sort an array of first names using JavaScript map function. Additionally, I aim to remove the "undefined" row from the final results: function contacts_callback(obj) { var contactinfo = obj.contacts .filter( ...

Fix a carousel layout problem

I've made changes to an HTML-PHP module to display portfolio images as a carousel, and I'm using the same module on this website too. However, I've encountered an issue with duplicate content and the previous-next navigation buttons. Can so ...

Finding out the RAM restriction of Docker for Mac through NodeJS

Understanding the Docker Limitation In our development setup, we utilize Docker for Mac to overcome the compatibility issues between Docker/Linux Containers and MacOS/Darwin/Unix. Docker for Mac employs a Linux virtual machine internally to run all contai ...

There will be no pop-up notification displayed if the product is already in the cart

When a product is added to the cart, the following code is used: addproduct(itemId) { this.showLoading = true this.$http.post('/shampoo', {'item': itemId}).then((response) => { swal({ title: "Success!", ...

Backand.com experienced a surprise encounter with an error 404 while utilizing the REST API

Working with my web app, I've integrated Backand.com as my MBAAS provider. All tables are linked and a data model has been set up. While querying the default REST APIs poses no issue, encountering a 404 error randomly happens when attempting to call ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...

The notion of await goes beyond simply waiting for a promise to be fulfilled

Hey there everyone! I've been struggling with a problem for some time now, and I just can't seem to figure it out by simply searching online. That's why I'm turning to all of you for help. Situation: I'm working on a small applic ...

How does the system automatically update the ordered list (1, 2, 3) when some list items are removed in between the numbers?

After removing an item, the order of list numbers is automatically updated but the item numbers are not synchronized with those numbers. I want the item numbers to be synced with the li numbers. "use strict"; var demo = angular.module("demo", []); fun ...

Using a while loop to chain promises in webdriver.io

I am trying to capture a full webpage screenshot by taking tiles of the viewport size. I have almost completed this task, but I am relatively new to promises and need guidance on the correct approach. Below is my code. The issue I am facing is that the ca ...

Updating the color of tick marks on checkboxes

I have successfully updated the background color of my checkboxes using a custom function. However, the tick mark on the checkbox now turns black instead of remaining white. How can I keep the tick mark white while changing the background color? Here is t ...