Multiple executions can be triggered by ng-checked function

Here is the code snippet from the view :

 <input type="radio" name="tabset" id="tab2" aria-controls="rauchbier"
        ng-checked="switch_tabs()">

And in the controller, we have:

   $scope.switch_tabs = function(){
        console.log(notification_form_data);
        console.log($('#notification_form').serialize());
        if (notification_form_data != $('#notification_form').serialize() && notification_form_data!= undefined)
        { 
            var alertPopup = $ionicPopup.alert({
            title: 'vs',
            template: 'unsaved data in actions',
            button: 'Done'

        });

    }

The alert prompt and console.log are triggered 100 times when a certain condition is met. How can we make it trigger only once?

Answer №1

Understanding the behavior of ng-checked on page load

When using ng-checked, it is important to remember that it works with boolean values. For example, you can use ng-checked="checkbox_checked" where the checkbox will be checked if checkbox_checked is true.

If you want an action to occur only once when a radio box is clicked, consider using ng-click to trigger your function.

Alternatively, you can monitor changes in a variable by utilizing $scope.$watch.

$scope.$watch('notification_form_data', function() {
   if (notification_form_data != $('#notification_form').serialize() && notification_form_data != undefined) { 
      var alertPopup = $ionicPopup.alert({
      title: 'vs',
      template: 'unsaved data in actions',
      button: 'Done'
     });
})

Another approach is to incorporate an ng-model with ng-change, which will execute your function when the model is altered. To conditionally run the alert based on the state of the radio box, check if the variable associated with the ng-model is true.

<input type="radio" name="tabset" id="tab2" aria-controls="rauchbier"
        ng-model="radio_checked" 
        ng-changed="switch_tabs()">
$scope.radio_checked = false
$scope.switch_tabs = function(){
        console.log(notification_form_data);
        console.log($('#notification_form').serialize());
        if (notification_form_data != $('#notification_form').serialize() && notification_form_data!= undefined && $scope.radio_checked)
        { 
            var alertPopup = $ionicPopup.alert({
            title: 'vs',
            template: 'unsaved data in actions',
            button: 'Done'

        });

    }

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

Retrieving user input through JavaScript and transmitting information using Ajax

UPDATE: Issue resolved by changing name="demo_name" and similar attributes on my form to id="demo_name". Thanks @Jill I'm attempting to save contact form data into a MySQL database using jquery's ajax feature. I'm new to this, and while it& ...

express-validator, no validation errors have been found so far

How can I verify if a given string is in the format of an email address? Here's a snippet of code that attempts to do so: req.checkBody('email', 'Invalid email address').isEmail(); var validationErrors = req.validationErrors(); i ...

Diverse Range of Exports Available in React Component Library

I have been working on developing a component library consisting of multiple independent components. My objective is to enable users to easily import and use these components in their projects, similar to the following: import One from 'component-lib ...

What is the best way to duplicate ng-tags-input within the angular ui-grid?

This is a code snippet that I created: // JavaScript code snippet var app = angular.module('app', ['ui.grid','ngTagsInput']); app.controller(&ap ...

Can someone explain the integration of socket.io and express in a simple way?

I am encountering an issue with socket.io emit and express. My goal is to emit data for a web game, specifically to send players data to a specific lobby. For instance, if I create a lobby at the following link: localhost:8000/test/lobbyName, I want to emi ...

Daily loop countdown timer

Looking to implement a daily countdown timer that ends at 10am, I have the following code set up: setInterval(function time(){ var d = new Date(); var hours = 09 - d.getHours(); var min = 60 - d.getMinutes(); if((min + '').length == 1){ ...

Activate a function to focus on an input field once ngIf condition becomes true and the input is revealed

I am currently attempting to focus the cursor on a specific input field that is only displayed when the condition of the surrounding ngIf directive is true. Here is an example of the HTML code structure: <div> <button (click)="showFirst = ...

One text label to display for a MultiLineString using MapLibre GL JS

I am attempting to show text labels for MultiLineString features within a geoJSON file using MapLibre GL JS. By utilizing the symbol-placement: point option, I aim to display the labels across various zoom levels rather than only when extremely close, as w ...

What are some examples that illustrate the differences between ng-if, ng-show, and ng-hide

While exploring ng-if, ng-show, and ng-hide, I realized that they all seem to serve a similar purpose. Why are there three directives when one might suffice? ...

The scope attribute is not functioning as expected in the loopback model

After utilizing an "include" : "organization" query within the context of my request.json file, a related model, I noticed that the resulting output from the query does not include the intended relation. The structure of the model (request.json file) is ...

The height map method for plane displacement is experiencing issues

The heightmap I have selected: Scene without grass.jpg map : Scene with grass.jpg map: https://i.sstatic.net/q6ScO.png import * as THREE from 'three'; import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js'; import ...

What is the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

A peaceful WCF service initiates a client callback whenever a server update occurs

In the process of developing a WCF RESTFUL service on top of a c++ console application, I am confronted with an issue. The client accesses this c++ application through my restful wcf service using a browser. Every time there is an update received by my w ...

Limited access textbox

Is there a way to create a text-box in AngularJS/HTML that is partially readonly? For instance, having the default value as "+91" and making it readonly while allowing users to enter additional values afterwards? ...

The process of uploading images to a server by making an AJAX call to a PHP file

I have an input file and I want to upload the attached file to the server with a message saying "uploaded successfully" when I click on the upload button. However, I am getting a "file not sent" message. (The uploaded images need to be saved in the uploa ...

Looking to leverage iframes in your Javascript code?

Currently, I am implementing a JSP popup window using JavaScript with an iframe to display a table of multiple records. However, when I disable the table of multiple records, it does not prevent the onclick function (hyperlink). The code snippet is provid ...

Javascript Object and Conditional Statement

I am working on a Dygraph object creation script that includes a data variable. However, I want to avoid passing in this variable for older browsers. Here is the code snippet: function prime() { g = new Dygraph( document.getElementById("g"), d ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. https://i.ss ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

Dealing with cross-origin error issues when using json.parse in React / MERN development

My data structure functions correctly when I use console.log: console.log(JSON.parse([values.category2]).needed_skills); However, when I pass the output of JSON.parse([values.category2]).needed_skills to a component in my application, the entire system c ...