execute a command from the controller

I'm working on an Ionic app and I have a login feature implemented. I want to display a spinner when the user clicks the login button, and hide it once the login process is complete. Here's my current code snippet: This is the scope function that triggers when the login button is clicked: $scope.doLogin = function(loginData) { console.log("in doLogin") $scope.submitted = true; if (loginData.$valid) { $ionicLoading.show({ template: '<ion-spinner class="spinner-energized" icon="spiral"></ion-spinner>', hideOnStateChange: true, duration: 2000 }); $location.url('/about'); } }; I want to modularize this functionality using AngularJS directives so that I can easily use it across multiple click events in my codebase. However, I'm unsure about how to approach this. You can find the code here: http://plnkr.co/edit/pi71uQunHSYMwONqlPTa?p=info Specifically, I want to encapsulate the following part into a directive for reusability: $ionicLoading.show({ template: '<ion-spinner class="spinner-energized" icon="spiral"></ion-spinner>', hideOnStateChange: true, duration: 2000 }); One challenge I'm facing is ensuring that the 'ionicLoading.show' is only triggered when 'loginData.$valid' evaluates to true. Any assistance or insights on how to achieve this would be highly appreciated. Thank you!

Answer №1

This particular structure allows for a single directive to be utilized across multiple HTML files in order to execute the ionicLoading function.

Within the directive:

angular.module('my.directives', [])
    .directive('mainDirective',['$ionicLoading', function($ionicLoading) {
      return function(scope, element, attrs) {
        element.bind("click", function() {
          console.log("directives")
          var a = scope.$apply(attrs.mainDirective)
          console.log(a)
          if(a ===true){
            console.log("inside inside")
                $ionicLoading.show({
                template: '<ion-spinner class="spinner-energized" icon="spiral"></ion-spinner>',
                hideOnStateChange: true,
                duration: 2000
            });
                switch (attrs.mainDirective) {
                    case "loginData.$valid":
                        scope.$apply("doLogin(loginData)")
                        break;
                    case "regForm.$valid":
                        scope.$apply("submitRegForm(regForm)")
                        break;
                    case "newData.$valid":
                        scope.$apply("createLoanApplication(newData)")
                        break;
                    case "pswdChange.$valid":
                        scope.$apply("submitPswdChange(pswdChange)")
                        break;
                    case "feedback.$valid":
                        scope.$apply('submitFeedback(feedback)')
                        break;
                }

          }

        });
      }
    }
    ])

Within one of the controller scopes that will use the directive function:

$scope.doLogin = function(loginData) {
    console.log("in doLogin")
    $scope.submitted = true;

      AuthenticationService.login(loginData);    
  };

In an HTML page where the directive is needed:

<div>
  <button main-directive = "loginData.$valid" class="button button-block button-positive" type="submit">Log in</button>
</div>

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

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

Retrieve information from individual XML nodes in a parsed string

When making an Ajax call to retrieve XML data from a different domain using a PHP proxy to bypass cross-origin restrictions, I am unable to extract the values from the XML nodes and display them in my HTML tags. Despite no errors showing up in the browser ...

Obtain the data of the highlighted row in a telerik grid directly from the client side

I am attempting to retrieve the value of a GridBoundColumn with DataField="id" using JavaScript on the client side. When the user clicks on the image button within a row, I need to extract the id for that specific row and then invoke a web method by passin ...

Instead of relying on traditional AJAX for receiving remote commands, consider using a new Image object in your code like this: `var

How efficient is the following method: var i = new Image(); i.src = 'http://secondary.domain.com/command.gif?command=somecmd&rand=' + ...epoch time....; ... utilizing mod_rewrite to redirect the above URL to a PHP script ... Is this an effe ...

Error: React.js encountering an issue where property 'map' is undefined and cannot be read

While following an online tutorial for React.js on controlled inputs, I am continuously encountering the error: TypeError: Cannot read property 'map' of undefined import CallRow from "./CallRow"; import React from "react"; class SearchPage ...

Issue: Receiving a status code 403 error - Suspected issue with Axios, consider using fetch instead

While using axios in a Next.js application that interacts with the Youtube API, I encountered an error. Here is the problem:https://i.sstatic.net/No0Nh.png Below is the code snippet: import React from "react"; import youtube from "./api&quo ...

In my Cordova application, I am able to print the locally stored JSON array, but I am encountering an issue where the

Hello, I'm having some difficulties with JSON as a beginner. I've tried searching extensively but haven't found a solution that works for me. My issue arises when attempting to save data using local storage in JSON format - the array prints ...

Can you utilize the "import as" feature with just a handful of exports?

I am trying to bring in just a few exports from a module using a namespace in order to avoid adding unnecessary bulk to my project. Is there a way to achieve this? import { FaUser, FaUsers, FaScroll } as FaIcons from 'react-icons/fa'; With this ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Leveraging JavaScript to enable automatic identification of buttons on a webpage

My website features specific buttons placed within articles and also in the head/body/footer sections. I have a plan to make it so that when a user clicks on a button, JavaScript code will determine if the button is inside an article or outside of it, then ...

What could be causing my ul list to not be populated by ajax?

To populate the ul list with data from PHP code on page load, you can use the following ajax function. I appreciate any help in advance, and please forgive me if my explanation is not precise as I'm new here. This post contains mostly code snippets. ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

What is the advantage of encapsulating a helper function within an IIFE instead of declaring it directly within the body of the function where it is being

Exploring the functionalities of Babel and ES6, I found myself stuck while transpiling some code at this particular section: class App extends SomeParent { myFunction() { } } I am curious about the output that caught my attention: var _createCl ...

In Javascript, the assignment of a custom property continues indefinitely instead of occurring just once

Currently, I have a JavaScript code snippet where I am attempting to create a promotion field within each of my promotion items. However, I am encountering an issue where it keeps nesting itself endlessly, whereas I only require it to contain one reference ...

Leap over in a similar fashion to the provided demonstration

In my attempt to create a unique project, I have created this CodePen example. The goal is to have one ball on the circle that remains in a fixed position, while another rotating main ball must avoid touching it at all costs. Points are awarded for success ...

Struggling to Fetch Data from REST API with ng-repeat in Angular JS

After making a REST call from Angular JS and receiving a response from the API, I am looking to display messages on the front end using ng-repeat in my controller. $http({ url: "http://localhost:8080/services/AddConfig", method: "POS ...

Creating a new object within a class in ECS6: A step-by-step guide

Just starting out with ES6, and I'm trying to figure out how to correctly instantiate new objects inside a class. Any guidance on the best approach for this? Also, I'm struggling with accessing the connection in the function getName(). I know I ...

Retrieve the output from the callback function and assign it to the parent function

Recently, I've started exploring Nodejs and javascript while working on a nodejs api code. As per project requirements, I am utilizing the GandiAPI to verify domain availability for domainA (Project specific requirement). In this process, I have devel ...

What is the best way to transfer the text from the input box to a div at the bottom of the page?

Recently, I came across a small piece of HTML containing two input boxes, a checkbox, and an "Add" button: <div class="row"> <div class="form-group col-xs-4"> <input type="text" class="form-control" id="items" na ...

Tips for utilizing jQuery buttons to submit forms in PHP

I'm struggling to submit the form using PHP from a button in jQuery. I've tried adding an ID for the button, but I can't seem to submit the values. Since I'm new to jQuery, this task is proving to be a bit challenging. Can anyone provid ...