execute the $scope.watch function only when the field loses focus

I am new to Angular and I am searching for a method to trigger a function only after the focus is out of the field, rather than after every change. The purpose of this function is to check if the user has modified the data in a specific <td> element, and only execute the function in that case. The issue currently is that every keystroke triggers the function, causing it to run multiple times.

This is the table structure:

<tbody ng-repeat="(user_id, script_id) in data">
    <tr ng-repeat="(script_id, cron_format) in script_id">
        <td class="userName">{{user(user_id)}}</td>
        <td class="scriptName">{{script(script_id)}}</td>
        <td class="cronFormat"><input type="text" ng-model="cron_format" ng-change="saveCron(user_id, script_id, cron_format)"/></td>
    </tr>
</tbody>

Below are the defined functions:

$scope.$watch('cron_format',function(x,old){
    if(x!=old){
    }
});

$scope.saveCron = function(userId, scriptId, cronFormat){

   $.post("updateCronChange.php",
        "user_id="+userId+"&script_id="+scriptId+"&cron_format="+cronFormat, 
         function(data){
        //inside post
            alert('Cron format changed to: '+cronFormat);
   });
}

Is there any Angular-specific way to call the saveCron() function only when the focus moves out of the field (cron_format)?

Answer №1

Another great workaround for Angular 1.3.x involves utilizing ngModelOptions to specify that the model should only update on the focusout event:

<input type="text" 
       ng-model="cron_format" 
       ng-change="saveCron()" 
       ng-model-options="{ updateOn: 'focusout', debounce: {'focusout': 0} }"/>

Answer №3

Instead of using the ng-change directive in the view, you can opt for the ng-blur directive. This way, the saveCron function will be triggered every time the input field loses focus.

Answer №4

To avoid using $watch, you can compare the values to another changed value. Utilize ng-blur to trigger the change check.

$scope.initial = $scope.timer_value = "";

$scope.updateTimer(user_id, task_id, timer_value) {
    if ($scope.initial == $scope.timer_value) {
        return; //value remains unchanged
    }
    $scope.initial = $scope.timer_value;
    $http.put();
}); 

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

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Exploring the effectiveness of testing Svelte components

Looking to test a component that utilizes a third-party module without mocking the imported components? Check out this example: // test.spec.ts import Component from "Component"; describe('Component', () => { test('shoul ...

Tips for ensuring the border matches the size of the image

I am in the process of creating a website that includes a filter option. My plan is to have the filters displayed on the left side and the items on the right side. To achieve this layout, I have implemented a scrollable div for the items. However, I notic ...

Adjust the burger menu color based on the background color of the section

Currently, I am working on creating a hamburger menu component with fixed positioning using the 'fixed' property. The menu icon consists of three white lines by default, but I want them to change to black when placed in a white section. I have tr ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

Confused about how to utilize the variable `${PORT}`?

Currently, I am following a tutorial in which the instructor inputs the following code snippet: let PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log('Server beating ...

Is there a way to convert HTML into a structured DOM tree while considering its original source location?

I am currently developing a user script that is designed to operate on https://example.net. This script executes fetch requests for HTML documents from https://example.com, with the intention of parsing them into HTML DOM trees. The challenge I face arise ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

What is the best way to incorporate this custom file upload button, created with vanilla JavaScript, into a React application?

Hey there! I have successfully implemented a custom file upload button using HTML, CSS, and JS. Now, I want to recreate the same design in React. Can someone guide me on how to achieve this in React? HTML Code: <br> <!-- actual upload which is h ...

Steps to deactivating a styled button using React's styled-components:

I've created a very basic styled-components button as follows: import styled from 'styled-components'; const StyledButton = styled.button``; export const Button = () => { return <StyledButton>Default label</StyledButton> ...

Switching images through onmouseover, onmouseout, and onclick interactions

I have two images named img1 and img2. Here is my code: function roll(id, img_name, event_name, img_id) { var state ; if(event_name == 'mouseover') { state = false;rollover();} else if(event_name == 'mouseout') { ...

Experiencing problems with the response from the Netlify Lambda function.. consistently receiving undefined results

I've been working on setting up a lambda function to handle authentication, validation, and sending of a contact form. As I'm new to lambda functions, my code might have some flaws. However, despite my efforts, I am struggling to modify the resp ...

The attempt to install "expo-cli" with the command "npm install -g expo-cli" was unsuccessful

Encountered an issue while trying to install expo-cli for creating android applications using npm install -g expo-cli. NPM version: 7.19.1 Node version: v15.14.0 Upon running npm install -g expo-cli, the installation failed with the following error mess ...

When working on my asp.net webform, I incorporated an AgreementCheckBox along with a CustomValidator. However, I encountered an issue where the error message

Code for AgreementCheckBox: <asp:CheckBox ID="AgreementCheckBox" runat="server" ForeColor="Black" Text="Please agree to our terms and conditions!" /> Code for AgreementCustomValidator: <asp:CustomValidator ID="AgreementCustomValidator" runat=" ...

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 ...

Displaying the Selected Value from the DropDown in the Menu

I am working with Bootstrap5 and have the following dropdown menu in my code. Instead of displaying "Year," I would like to show which member was selected. How can I achieve this? <div class="dropdown"> <button class="btn btn- ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Automatically append a version number to destination output files using the Grunt task runner

We have a package.json file that contains our version number, like this: { name: "myproject" version: "2.0" } The objective is to dynamically insert the version number from the package.json file into the output files. Instead of manually updating ...

How can I implement a confirmation modal in Flask for deleting actions?

In my Flask application, I have a page that includes a link to delete a specific item. Each row in a table has a unique ID, which is typically used for deletion. Here is the code snippet for the link: <button type="button" class="btn btn- ...

Having issues incorporating Redux into React Native application

Struggling to make a small app work in React Native with Redux. It was functioning fine without Redux, but after attempting to integrate Redux, it now shows a blank white screen and a loading message. I want to avoid using classes and stick to functional p ...