When using ng-click, each function is executed only a single time

After creating a function that combines two separate functions (recorder.start() and recorder.stop()), I encountered a problem where the program could only fire one of the functions at a time when they were added to one ng-click. This meant that in order for the second function to be executed, I had to press the button again. Is there a way to get both functions to execute after pressing the button just once?

Here is the JavaScript code:

$scope.record = function() {
        recorder.start($scope.recordConfig).then(function() {
            var test = $scope.recordConfig.captureSource;
        recorder.stop();
        })
    },

n.start = function(e) { 
        return t.postMessage("start", e)
    }, 

n.stop = function() {
        t.postMessage("stop")
    }, 

c.postMessage = function(e, t) { 
            return c.getPort().then(function(n) { 
                return n.postMessage({
                    type: e, 
                    data: t
                })
            })
        },

And here is the HTML code:

<md-button ng-click="record()" class="md-primary md-raised">Start Recording</md-button>

=======================================================================

  • Further question: I attempted to control the two functions with a piece of code in popup.html.js, but ran into an issue where the popup window closed when the user changed tabs in Chrome. The Chrome documentation explained that "popups automatically close when the user focuses on some portion of the browser outside of the popup." Do you have any suggestions on how to keep the popup window open at all times, or enable the stop() function to run even when the popup window is closed?

Here is the code from popup.html.js:

    $scope.recordStart = function() {
       // recorder is an angular module which can postMessage such as start/stop/pause... ...

       recorder.start($scope.recordConfig)
        .then(function() {
            var test =  $scope.recordConfig.captureSource;
            "tab" !== test && "desktop" !== test || a.IS_E2E;
        })     


$scope.stop = function() {
        recorder.stop();
    }, 

$scope.record = function() {
      $scope.recordStart();
        $timeout(function(){$scope.stop(); },4000)
 }

Answer №1

This code snippet demonstrates how to execute two functions with a single click by utilizing $timeout.

Within the "CallFun" function, we utilize $timeout to automatically call "fun2()" after a 2-second delay.

You also have the option of achieving this using API calls.

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

app.controller("ctrl", function($scope, $timeout){
  $scope.fun1 = function(){
    $scope.message = "Returned from function 1"
  }
  
  $scope.fun2 = function(){
    $scope.message = "Returned from function 2"
  }
  
  // Following is an example of manual timeout
  $scope.callFun = function(){
    $scope.fun1();
    $timeout(function() {
      $scope.fun2();
    }, 2000);
  }  
});
<html>
  <head></head>
  <body ng-app="app" ng-controller="ctrl">
    
    <button ng-click="callFun()">Click to execute functions with $timeout</button>
    
    {{message}}
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </body>
</html>

Answer №2

When working with functions, it is important to pay attention to the parameters being passed, especially when using callbacks. Sometimes, you may inadvertently inject a parameter and treat it as a callback. One way to address this is by nesting functions within one another.

For example:

$scope.mainFunction = function(){
    $scope.innerFunction1();
}

$scope.innerFunction1 = function(){
    $scope.innerFunction2();
}

$scope.innerFunction2 = function(){
  //your code here
}

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

Preventing the cascading effects of past hovers with AngularJS

I am working with AngularJS and have the following HTML code snippet. <div class="row" style="margin-left:60px; text-align:center;"> <div class="col-xs-1 " style="margin-left:25px;width:10px; " ng-repeat="image_thumb_id in image_thumbnail_ ...

Retrieve a particular HTML element from an object that has been mapped

After reproducing my issue on a smaller scale for easier handling, I am now aiming to implement an onclick function that reveals the hidden content inside each column. The plan is to initially hide the content using display: none and then switch it to disp ...

How can we efficiently validate specific fields within arrays and objects in express-validator by utilizing the body() method?

I have organized my field names in an array as follows: const baseFields = [ 'employeeNumber', 'firstName', 'lastName', 'trEmail', 'position' ]; These are the only input fields I need to focus on for valid ...

What issue is present in this Node.js one-line conditional statement?

Check it out: ( result.username === user.username ) ? res.status( 500 ).json( "That username is already taken." ) : res.status( 500 ).json( "That email has already been used." ) Shouldn't this execute the first part, res.status( 500 ).json( "That us ...

Type of element returned

Is there a way to retrieve the element type? I'm interested in applying the style of a class to HTML5 elements without using the class attribute. <!DOCTYPE> <html> <head> <title>My page</title> </head& ...

Ways to insert HTML text into an external webpage's div element without using an iframe

Is it possible to generate HTML and SVG code based on the position of a Subscriber on a web page or within a specific div? I would like to provide some JavaScript code that can be inserted inside a particular div on the page. Using an iframe is not ideal ...

Inserting an icon into a particular class

I am new to JavaScript and I am eager to understand the code I write rather than just using it. That's why I'm turning to this forum with a question regarding adding an icon to a colored group. Here is the code snippet I have: <strong> ...

Having trouble rendering a model using OBJLoader in React Three Fiber

I'm having issues with rendering an .obj file in my React project using the OBJLoader and useLoader() hook from React Three Fiber. Despite ensuring that my file path is correct and wrapping the Model component in Suspense tags, I am still encountering ...

Leveraging the power of node.js, express, and handlebars to seamlessly render multiple views within a

I'm interested in finding out if there is a way to render multiple views using the res.render() function or another method. In the home.handlebars file, I currently have the following code: <h1>Home</h1> and I would like to display it i ...

Steps to include all dependencies in an angular application

Managing a large Angular application can be challenging. I currently use npm install to install all packages and manually load them in my index.html file, like this: <script src="node_modules/angular/angular.js"></script> Similarly, I load ot ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...

Retrieve specific components of objects using a GET request

When visitors land on my web app's homepage, a GET request is triggered to fetch a current list of Stadiums stored in the database through my API. However, the Stadium objects retrieved are packed with unnecessary data, particularly extensive arrays o ...

Troubleshooting: Ineffective use of replace() function on input value with jQuery

Visit this link for a demo How can I update the input value based on user selection in a dropdown menu? The objective is to change the value from "service_######" to "membership##_####" when the user selects YES, but my current JavaScript code using repla ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

Convert the value to JSON format by utilizing the PHP GET method

After retrieving a value using the GET method in my PHP file, I am attempting to access it. Below is how my PHP file appears: <?php include 'Con.php'; header('content-Type: application/json'); $catid = $_GET["CatId"]; //array ...

Avoiding the use of numbers in v-if in Vue.js

My website features a left menu that displays different content based on the selected menu's ID. However, I currently have === 0 and === 1 in the v-if statement, and I'm looking for a way to avoid manually inputting these numbers. <template& ...

I am looking to modify various attributes linked to Rails

My Desire for Reality I am looking to update multiple related values in Rails by sending an update request from JavaScript. While creating data was seamless, I encountered difficulties when attempting to update it. #Code JavaScript* export const actions ...

Enhance your website with jQuery's animate() feature for dynamic

My current implementation of jQuery's animate function looks like this: var css1 = { display: "block", marginTop: 20 }; var direction = "marginTop"; $(element).animate(css1, 150, 'swing'); I've noticed the marginTop ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Exploring and accessing elements and nested objects within a dynamically named element in JavaScript using JSON syntax

Receiving a JSON response from an API, here's what the data looks like: [{ "order_id":"1111", "restaurant_id":"ABC", "fullfillment":"Delivery", "order_channel":" ...