Using radio buttons in a popup on Ionic framework

Controlling Food Choices

.controller('FoodController', function($scope, $ionicPopup) {
    $scope.favorite = { 'food': 'egg' };

    $scope.setFavoriteFood = function() {
        var popup = $ionicPopup.show({
            'templateUrl': 'popup-favorite.html',
            'title': 'Favorite Food',
            'subTitle': 'Please pick your favorite food',
            'scope': $scope,
            'buttons': [
                {
                    'text': '',
                    'type': 'button-assertive icon ion-close-round'
                },
                {
                    'text': '',
                    'type': 'button-balanced icon ion-checkmark-round',
                    'onTap': function(event) {
                        console.log($scope.favorite.food);
                        return $scope.favorite.food;
                    }
                }
            ]
        });

        popup.then(function(result) {
            console.log('Your favorite food is: ' + result);
        });
    };
}

Custom Popup Template

<script id="popup-favorite.html" type="text/ng-template">
    <ion-list>
        <ion-radio ng-model="favorite.food" ng-value="egg">Egg</ion-radio>
        <ion-radio ng-model="favorite.food" ng-value="tomato">Tomato</ion-radio>
    </ion-list>
</script>

The issue with the data binding between $scope.favorite.food and radio buttons has been identified. Interestingly, replacing the radio buttons with a single input field

<input type="text" ng-model="favorite.food">
resolves this problem.

How can I ensure that my radio buttons function correctly as expected?

Answer №1

One suggestion is to consider including a string within the quotes

  <ion-radio ng-model="favorite.food" ng-value="'egg'">Egg</ion-radio>
   <ion-radio ng-model="favorite.food" ng-value="'tomato'">Tomato</ion-radio>

This example was sourced from :http://ionicframework.com/docs/api/directive/ionRadio/

The absence of quotes may indicate the expectation to connect to $scope.egg and $scope.tomato.

To explore a dynamic approach, you could modify your code to allow for radio buttons to be generated dynamically as shown in this example on the angular docs: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D

Answer №2

When utilizing $parent in ng-model, the issue is resolved.

<script id="popup-favorite.html" type="text/ng-template">
        <ion-list>
           <ion-radio ng-model="$parent.favorite.food" ng-value="'egg'" ng-change="test(formData)" >egg</ion-radio>
           <ion-radio ng-model="$parent.favorite.food" ng-value="'tomato'" ng-change="test(formData)">tomato</ion-radio>
        </ion-list>
</script>

Answer №3

When working with radio buttons, a single input won't cut it - you'll need to have multiple options available. One way to achieve this is by expanding your existing object like so:

JS

 $scope.favourites = [
    { food: "egg", value: 1 },
    { food: "tomato", value: 2 },
    { food: "cheese", value: 3} ]

HTML

<script id="popup-favorite.html" type="text/ng-template">
     <ion-radio ng-repeat="item in favorites"
                ng-value="item.value"
                ng-model="favourites.food"
                ng-change="doSomething(item)">
                {{item.food}}
     </ion-radio>
</script>

To ensure the data for food can be accessed across different views/controllers, consider implementing a service (if you haven't done so already).

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 duration from when the Ajax request is sent to when the response is received results in

Has anyone experienced strange results when measuring the time between sending and receiving an ajax request? Sometimes I get negative values. Can someone shed light on this peculiar behavior? var before = 0; var after = 0; $.ajax({ url: 'data.ph ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...

callback triggering state change

This particular member function is responsible for populating a folder_structure object with fabricated data asynchronously: fake(folders_: number, progress_callback_: (progress_: number) => void = (progress_: number) => null): Promise<boolean ...

Setting up the data for the AjaxAppender Request Log4Javascript

I am completely new to Log4Javascript and the concept of logging, so please bear with me. My current task involves sending logs to a CouchDB server using a POST request. However, I keep encountering an error from the server: {"error":"bad_request","reaso ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Tips on utilizing ajax to load context without needing to refresh the entire page

As a beginner in AJAX, I have some understanding of it. However, I am facing an issue on how to refresh the page when a new order (order_id, order_date, and order_time) is placed. I came across some code on YouTube that I tried implementing, but I'm n ...

Mastering the functionality of array.map()

Apologies for the simplicity of my query. I am in the process of streamlining some code and have been exploring the use of array.map rather than traditional for loops to iterate through arrays and using array.push. I've managed to grasp the fundament ...

Confirming the failure of google reCaptcha validation

I am experiencing issues with Google reCaptcha, My goal is to have the captcha function like this Essentially, I want the user=value to be hidden in the login form of Google Captcha For example - <input name="user" type="hidden" value="VALUE"> Wh ...

What is the process for AngularJS to automatically populate the initial tag value in an SVG template?

I'm currently working on an AngularJS directive that needs to update different attributes within an svg tag. angular.module("complexNumbers") .directive("cartesianPlane", function() { return { restrict: "E", scope: { }, templateUrl: " ...

Saving data in JSON format at a particular location

My JSON data contains various items that need to be placed in specific positions within a form. Is it possible to achieve this? var objs = [{ "Object1": { "ID": 1, "type": "input", "color": "red", "Text": "DARKDRAGON", "wid ...

Perform a task upon clicking the JavaScript menu

Implementing dropdown menu items using a text link with JavaScript and CSS. You can view a demo here. I am looking to trigger an action when each menu item is clicked. Currently, they are not behaving as expected. HTML: <span class="inline-dropdown- ...

EJS failing to render HTML within script tags

Here is some code that I'm working with: <% // accessing content from a cdn api cloudinary.api.resources( { type: 'upload', prefix: '' }, (error, result) => { const assets = result.r ...

Exploring the wonders of fs.readdir, fs.readfile, and the power

This application is built on Node with an express server. It contains a directory filled with text files, and the goal is to extract lines that contain the word "SAVE" from each file. Unfortunately, I've hit a roadblock in this process. app.get(&apo ...

Utilizing the Bootstrap Carousel tied to a specific slide index

Here is a simple HTML page I have created. <html> <head> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css&quo ...

Passing a dynamic value to a modal in AngularJS: A guide to enhancing user interaction

I'm attempting to send dynamic parameters to a modal by clicking a button, but some values are not being captured correctly and returning empty. Below is the snippet of my modal: <div id="<%handler%>" class="modal fade"> <div clas ...

Executing a JavaScript function when an HTML page is loaded within an OBJECT Tag

I have a situation where I am loading an HTML page inside an object tag. Since the iPad does not support iFrames, I decided to use the object tag to load external HTML pages into a container. Everything is working well so far, but now I want to be able t ...

Successive Alerts with Material-UI and React-Redux

After realizing that having multiple snackbars scattered across different components was messy, I decided to revamp my app by creating a single custom component that can be called using Redux to display any type of snackbar needed. Desired outcome: I exp ...

React: Issue with array rendering order after initial render

After the initial rendering of my array in the correct order, any subsequent changes to it result in the same rendered order. Let's consider this scenario: initializeArray() { this.state = { test_array: [1,2,3,4] } let self = t ...

Is it possible to turn off ajax within an iframe?

I'm currently developing a project that allows users to customize their page. What is the best way to prevent ajax functionality without having to disable javascript in an iframe? ...

Running JavaScript code within views

While dealing with AngularJS, I have an index page that includes a <div ui-view></div>. When a specific URL like #/offers/new is entered, it loads a page such as new-offer.html into the ui-view. In my javascript code block within the index.htm ...