inject a function to a filter in AngularJS

When applying a filter on the controller to retrieve data from a web API, everything works correctly. However, I am trying to implement a function that will be called from the controller when the filter searches for records and finds no data.

    .controller('statement_ctrl',function($scope,$http,$ionicLoading,$ionicPopup,$cordovaToast,$location,$ionicModal,$filter){
        $scope.account_number=localStorage.getItem("account_number");
            ///alert if connection fails
            $scope.connect = function() {
            var alertPopup = $ionicPopup.alert({
            title: 'Error',
            template: '<p align="center">Problem Contacting Server</p>',
            });
            };


        $scope.nobill = function() {
                    var alertPopup = $ionicPopup.alert({
                    title: 'Error',
                    template: '<p align="center">Billing not Found</p>',
                    });
                    };

        $scope.state_request= function(){
        $ionicLoading.show({template: '<p>Processing Request</p><ion-spinner></ion-spinner>'});
        $http.post("http://myprojec/statement.php",{'id':$scope.account_number}).success
        (function(data){
        console.log(JSON.stringify(data));
        $scope.record=data;
        $scope.test='results';
        //console.log(JSON.stringify(results));
        {$ionicLoading.hide();}
            })

     $scope.from = $filter('date')($scope.sdate, "yyyy-MM-dd"+'T00:00:00')+'Z';
      $scope.to =  $filter('date')($scope.edate, "yyyy-MM-dd"+'T00:00:00')+'Z';


            }

    })
.filter('dateRange', function() {
    return function(records, from, to, nobill) {
      // return empty array if input not defined or not array
      if(!records || !angular.isArray(records)){
         return [];
      }
      var results = records.filter(function(record) {
         // run console log tests here...before the return
        return record.Date >= from && record.Date <= to;  
         console.log(test)     
      });
      if(results.length==0){
          nobill();
          }else{
              console.log('this is records in there')
              }
      console.log( 'Number of results:', results.length);
      return results;
    }
})

HTML

<form method="post" name="statement" id="statement">
<div class="list">
  <label class="item item-input">
    <span class="input-label">Search From</span>
    <input type="date" ng-model="sdate" required="required">
  </label>
  <label class="item item-input">
    <span class="input-label">Search To</span>
    <input type="date" ng-model="edate" required="required">
  </label>
</div>
</form>
</br>
<div align="center">
<p><button class="button button-positive" ng-disabled="statement.$invalid" ng-click="state_request()">
  <i class="icon ion-android-search icon"></i> Search
</button></p>
</div>

If the length equals zero, I want to call the nobill function from the controller to the filter. Despite attempting to do so, an error stating that nobill is not a function occurred.

Answer №1

 var APP = angular.module('MYAPP');

APP
.factory('myDateSvc', [function() { // defining a service here
    return {
        dateRange: function(records, from, to, nobill) {
            ... custom code goes here ...
            nobill();
        }
    }
}])
.controller('statement_ctrl', ['$scope', 'myDataSvc', function($scope, myDataSvc) {
    ... more code here ...
    $scope.nobill = function() { ... };

    myDataSvc.dateRange(recordsVal, fromVal, toVal, $scope.nobill);
    ... additional code snippets ...
}]);

This snippet provides a skeleton for creating and using a service in AngularJS by injecting it into a controller and calling a method from the service with a callback function. The code may need some adjustment for your specific requirements, but it should give you a starting point.

This is a basic example of how you can implement this functionality. I hope it helps!

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

Exploring the concept of JavaScript nested promise scopes within the context of AngularJS

I've been struggling with JavaScript promises for the past few hours, trying to fix a problem that I just can't seem to solve. My knowledge of promises is limited, so I'm open to the possibility that my approach might be incorrect. Currentl ...

Using JavaScript, generate table rows and cells

Hey there, I'm struggling with formatting my table correctly within the designated section. Currently, it's printing the rows one below the other instead of creating a 'tr' and multiple 'td' elements for each input field. The ...

Utilize AJAX request to populate a datatable with JSON data and incorporate hyperlinks for seamless

Below is the datatable java script I am using: $('#Proj_emp_table').dataTable({ "sAjaxSource": "/projects/project_json/", "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { ...

Guide on sending AJAX requests from Javascript/React to Python REST API and receiving data

In my project, I have developed the front end code using React. There is a simple form where users can input their name, title, department, and other basic string fields. Upon hitting submit, JavaScript triggers an AJAX request to my REST API which is impl ...

Make SVG Path (Vector Graphic) Simplification easier

Provided Input: <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="800pt" height="600pt" viewBox="0 0 800 600"> <g enable-backgrou ...

No elements present in TypeScript's empty set

Question for discussion: Can a type be designed in TypeScript to represent the concept of an empty set? I have experimented with defining one using union, disjoint union, intersection, and other methods... ...

Here's a unique rewrite of the text: "What is the best way to run a JavaScript script in Java and

Currently in the process of automating a web application that utilizes SmartClient, I am in need of a reliable method for constructing locators for forms and populating input fields. Our testing framework is based on Selenium and SmartClient's scLocat ...

JavaScript parameter not found

I am currently working on a block type plugin for Moodle and encountering some difficulties with my JS code. Due to my limited knowledge in JS and JSON, I am having trouble identifying the issue at hand. My code includes a function that adds a custom actio ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

After completing the installation of "node-pty" in an electron-forge project on Linux, I noticed that the pty.node.js file is not present. What is the proper way to install node-pty

Following the installation of node-pty, an external module utilized to generate pseudo terminals with Node.js in a boilerplate electron-forge project, I encountered an issue. The error indicated that a core module within node-pty was attempting to import a ...

New customer not showing up on Stripe dashboard

My ecommerce website is integrated with Stripe, and despite having error-free code, I am facing an issue where new customers are not getting registered in my Stripe dashboard. It used to work fine at one point, but now it's not functioning properly. ...

Exploring the capabilities of d3 within an Angular service

Having a d3 visualization inside my directive led to the realization that there is a significant amount of repetitive code that could be utilized in multiple visualizations. One solution was to create a service to handle the tasks typically done within the ...

Move the items downwards to occupy any empty space vertically

Just a quick overview of the code I'm working with (I am using Material UI in React). This container is meant to hold chat messages exclusively. const ChatContainer = ({ chatMessages }) => { const classes = useStyles(); return ( <Paper ...

How to apply styling to a specific portion of text within a list element using Vue.js

Despite my best efforts, I am struggling to style only the word "healthy" within the 'It is healthy!' string using computed properties, watchers, and methods in vuejs. I'm at a loss for how to achieve this unique styling. <template> ...

The Await function is incompatible with MongoDB collections

Struggling with retrieving the current collection from mongodb. A file contains a FetchUsers function that returns a user collection: const mongoose = require('mongoose'); const uri = "mongodb+srv://<username>:<password>@<cluster- ...

Adjust the width of the child element to match the parent div's dimensions

In my current setup, there is a parent div that contains a table as a child element. To tidy up the appearance, I am using CSS to hide certain columns in the table rather than applying inline styles. My question is how can I adjust the width of the paren ...

The Codepen demo for SemanticUI is not functioning properly

Click here to view the example on CodePen $('.ui.sidebar').sidebar({ context: $('.bottom.segment') }) .sidebar('attach events', '.menu .item'); I am currently trying to replicate this specific functiona ...

Discovering the method to access a getter from a different JavaScript file

In a laravel + vuejs project, I am trying to access my currentUser role in my Acces.js file using store.getters.currentUser but encountering an error: Error in render: "TypeError: Cannot read property 'getters' of undefined I have tried mu ...

Having trouble with retrieving data in list format from a JSON file

Having recently entered the realm of the ionic framework, I find myself facing a particular challenge: The data.json file consists of: { "speakers" : [ { "name":"Mr Bellingham", "shortname":"Barot_Bellingham", "reknown":"Royal Academy of P ...

Explanation on subtracting the row value from a textbox

Click here to view the image For instance: If I enter a value in the "USED(kl)" textbox, it should subtract that value from the corresponding row where "KILOGRAM/S" is located; Upon clicking the update button, only the specific row should be affected wh ...