How can I simultaneously execute two functions, one while the page is reloading/refreshing and the other on ng-click?

Here is the code snippet for the controller functions related to payment status.

$scope.userhold_payment = function() {
    $http.get('http://localhost/ngaffiliate/api/payment/change_hold_payment_status')
        .then(function(response) {
            console.log('User hold payment called');
            $scope.userhold = response.data;
        });
};

$scope.check_status = function() {
    $http.get('http://localhost/ngaffiliate/api/payment/check_payment_status')
        .then(function(response) {
            console.log('Check payment status called');
            $scope.checkstatus = response.data;
            console.log(response);
            console.log($scope.checkstatus.is_hold_payment);
        });
}

Below is a section from main.html which triggers these functions:

<div ng-init="check_status()">
    <button type="button" ng-click="userhold_payment()" class="btn-success btn-lg hold_payment_html" style="margin-top:7px; font-size:16px">Hold Payment</button>
</div>

I am looking for help on how to initialize the check_status() function upon reloading and trigger the userhold_payment() function only when the button is clicked. Thanks in advance!

Answer №1

Consider trying this approach:

$scope.userhold_payment = function() {
    $http.get('http://localhost/ngaffiliate/api/payment/change_hold_payment_status')
        .then(function(response) {
            console.log('Function called successfully');
            $scope.userhold = response.data;
            // console.log($scope.userhold.is_hold_payment);
        });
};

// This function will be triggered whenever the controller is reinstantiated
($scope.check_status = function() {
    $http.get('http://localhost/ngaffiliate/api/payment/check_payment_status')
        .then(function(response) {
            console.log('Reinstantiation success')
            $scope.checkstatus = response.data;
            console.log(response);
            console.log($scope.checkstatus.is_hold_payment);
        });
})();

HTML snippet:

<div>
    <button type="button" ng-click="userhold_payment()" class="btn-success btn-lg hold_payment_html" style="margin-top:7px; font-size:16px">Hold Payment</button>
</div>

Using a controller is recommended over using ng-init.

Answer №2

To achieve this, utilize the window onload event as shown in the code snippet below.

var app = angular.module("myapp",[]);

app.controller("demoCtrl",function($scope,$window){

  $window.onload = function(){
   alert("load event");
  }
  $scope.clickFunction =function(){
    alert("ng-click event");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="demoCtrl">
  <div>
   <button ng-click="clickFunction()">click</button>
  </div>
</div>  

Answer №3

To properly initialize the data, it is recommended that a function call is made within the controller. By incorporating a module such as ngStorage, you can easily persist data through page refreshes with minimal effort.

$scope.check_status=function(){
   $http.get('http://localhost/ngaffiliate/api/payment/check_payment_status')
      .then(function(response){
          console.log('I called now')
          $localStorage.checkstatus = $scope.checkstatus = response.data;
          console.log(response);
          console.log($scope.checkstatus.is_hold_payment);
        });
}
if ($localStorage.checkstatus){
    $scope.checkstatus = $localStorage.checkstatus;
}
else{
    $scope.check_status();
}

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

Implementing Do Not Track in an express application

I am trying to implement a feature named "consent" in my Nodejs express app that utilizes the Do Not Track (DNT) functionality from browsers. This function is supposed to integrate Google analytics on rendered pages only when DNT is not active or its state ...

Troubleshooting Issue with Bootstrap 4 Modal Varying Content Display

Dealing with a minor issue where I'm unable to get a modal to fetch data from an HTML table and populate it into a Bootstrap 4 Modal. I've attempted various methods as evident in the code snippets below. Currently in a learning phase, I need to ...

JSON Error: Attempting to access the value of a key that is undefined

I've been working with an API and managed to successfully load a JSON array of objects in my browser. Here's a snippet of what it looks like: 0: source: {id: null, name: "Protothema.uk"} author: "james bond" title: " A TITLE" description: "A DES ...

When running scripts, Protractor is unable to perform a click action in Safari, even though it works perfectly in

Currently, I am in the process of developing an angular application and utilizing directconnect for Chrome and Firefox. All my test scripts are functioning as expected, however, a new requirement has been introduced to run these same tests on Safari. To ...

Navigation menus are being highlighted

I'm having trouble figuring out why my program isn't working as expected. The onmouseout event doesn't seem to trigger when hovering over an image in the menu... Check this link for more information Below is the code snippet causing the is ...

What is the best way to allow a number to be editable when clicked on in a React application

Currently, I am trying to find a solution for making a number editable when clicked without having to use form inputs or other React libraries that don't fit my requirements. The provided screenshots showcase the desired interface. https://i.stack.im ...

Executing a Python function using JavaScript: Step-by-step guide

I am facing an issue with invoking my python function from my javascript file. Running a simple server with python3 -m http.server, I have no backend and all my javascripts are on the front end. In a python file named write.py, there is a function that I ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

User Interface Pop-up dialog in AngularJS

I have a form for user registration located within a modal window. After submitting the form in the modal, I want to add the saved item to the array $scope.lists = []. This array is managed by the ListsController and the submission function is handled by t ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

Error: The function of forEach is not applicable to todoList

_serilizedList(todoList){ let serialized = '*My to-dos:*\n'; todoList.forEach((t, i)=> { serialized += '*${i}* - ${t}\n'; }); return serialized; } Unexpected TypeError: todoList.forEach is not ...

Tips for reducing the minimum height and weight of a GridStack grid component

Currently, I am utilizing the GridStack.js library and facing an issue with implementing keyboard functionality. When I decrease the screen width (using Chrome DevTools) to less than 800-1000px, all the grid elements automatically adjust their width to 100 ...

Hide the 1, 2, 3 page buttons in Datatables pagination and instead display only the Next and Previous buttons for navigation

I recently implemented datadables.net pagination for my HTML table. I am looking to customize the pagination buttons by hiding or removing the 1, 2, 3 ... buttons and only display Next and Previous Buttons. Is there a way to achieve this by setting paging ...

What causes the "Unknown provider: defaultFilterProvider <- defaultFilter" error in AngularJS when using angular-filters?

After incorporating angular-filters into my application.js, I am encountering the following error: Unknown provider: defaultFilterProvider <- defaultFilter Can someone advise on how to resolve this issue? ...

Class methods cannot be invoked within their constructor

I'm currently facing challenges with implementing my express router. This is a "subrouter" of my main router, hence I need to extend express.Router. Here's an example of the code (simplified to include only one method): import express from "expr ...

Having trouble transforming the JSON object into a usable format

Although I'm still getting the hang of JSON, please bear with me if this seems like a rookie mistake. My approach involves sending a query to a local file that performs a cURL operation on an external site's API and returns a JSON object. Due to ...

Creating a seamless navigation experience with Next.js: Implementing per-page layouts for efficient 2-link navigation on a single screen

In my next.js project, I have a URL like "http://localhost:3000/forum". If a user goes to "http://localhost:3000/forum/{postId}", I want to redirect them back to "http://localhost:3000/forum" My folder structure is in the 'App' directory and I h ...

An array of length x containing keys of JavaScript objects

I'm currently working on a generator for chartjs to help me with creating datasets. My approach involves using object keys to extract data from each element in an array. Each element in the array may contain nested objects like this: https://i.ssta ...

Saving JSON data as a file on server

Currently, I am running a localhost website on my Raspberry Pi using Apache and I am seeking advice on how to export a JSON string to a file on the Raspberry Pi itself. While I do know how to export a file, I am unsure of how to send it to the Raspberry Pi ...

Various progress bars alter their appearance

<tr ng-repeat="data in data.names"> <td> <progressbar class="progress-striped" value="data.value.marks" type="dynamic value">{{ data.value.name }}</progressbar> </td> </tr> ...