The ng-value directive in Angular does not function properly when used with radio input elements

There are 3 radio inputs connected to ctrl.poiType, where ctrl represents the controller and poiType is an integer. The value of ctrl.poiType can be one of three constants defined as (ctrl.TYPE_TRIP, ctrl.TYPE_EVENT, ctrl.TYPE_POI).

To set up these input radios, ng-model and ng-value are used in the following way:

<label class="btn btn-default">
    <input type="radio" autocomplete="off" 
           ng-value="ctrl.TYPE_TRIP"
           ng-model="ctrl.poiType"  
           ng-change="ctrl.alert()"/>itinerary
</label>

The radio button should be checked if the value of ng-model equals ng-value, but this functionality is not working. The reason behind this issue is unclear.

[UPDATE] Here is the correct JS Fiddle link for reference.

Answer №1

If you're looking to ensure that the selected button appears active when clicked, and you're utilizing Bootstrap styles without the Bootstrap javascript component, you'll need to handle this within Angular yourself.

To show a radio button as "checked," you need to apply the active style to the label's class list.

Applying .active for Preselected Options:

To mark preselected options, you'll have to manually add the .active class to the input's label.

In Angular, dynamically modifying an element's class list can be accomplished using ng-class. Refer to the directive documentation for various options on how to implement it effectively.

I've made adjustments to your example by incorporating the ng-class directive, resulting in the button reflecting its active state upon clicking.

Although I don't suggest directly assigning CSS classes in your controller, this serves as a starting point for determining the optimal approach based on your scenario.

View

<div>poiType is set to 0, hence the first button will be selected
    <div ng-controller="TodoCtrl as ctrl" style="margin-bottom: 5px; padding: 5px; width:100%;">
        <div class="btn-group btn-group-justified">
            <label ng-class="ctrl.class(ctrl.TYPE_POI)">
                <input type="radio" ng-value="ctrl.TYPE_POI" ng-model="ctrl.poiType" />POI</label>
            <label ng-class="ctrl.class(ctrl.TYPE_TRIP)">
                <input type="radio" autocomplete="off" ng-value="ctrl.TYPE_TRIP" ng-model="ctrl.poiType" />itinerari</label>
            <label ng-class="ctrl.class(ctrl.TYPE_EVENT)">
                <input type="radio" autocomplete="off" ng-value="ctrl.TYPE_EVENT" ng-model="ctrl.poiType" />eventi</label>
        </div>ctrl.poiType = {{ctrl.poiType}}</div>
</div>

Controller

angular.module('epoiApp', [])

    .controller('TodoCtrl', function () {
    this.poiType = 0; // initializing first button selection

    this.TYPE_POI = 0;
    this.TYPE_TRIP = 1;
    this.TYPE_WAYPOINT = 2;
    this.TYPE_EVENT = 3;
    this.class = function (poiType) {
        if (poiType == this.poiType) {
            return 'btn btn-default active';
        } else {
            return 'btn btn-default';
        }
    }
});

Check out the working example on fiddle.

Answer №2

Success! I have gotten it to function:

<div ng-app="myApp">
  poiType starts at 0, ensuring the first button is selected
  <div ng-controller="TodoCtrl"
       style="margin-bottom: 5px; padding: 5px; width:100%;">
    <div class="btn-group btn-group-justified" 
         data-toggle="buttons">
       <label class="btn btn-default">
          <input type="radio"  ng-value="TYPE_POI"
               ng-model="poiType" 
               ng-change="popup()"/>POI
        </label>
        <label class="btn btn-default">
           <input type="radio" autocomplete="off" 
                  ng-value="TYPE_TRIP ||
                            TYPE_WAYPOINT "
                  ng-model="poiType"  
                  ng-change="popup()"/>itinerari
        </label>
        <label class="btn btn-default">
          <input type="radio" autocomplete="off"  
                 ng-value="TYPE_EVENT"
                 ng-model="poiType" 
                 ng-change="popup()"/>eventi
        </label>    
     </div>         
   </div>         
</div>

To make this work, you must set up a module for your Angular application to reference. In this case, I named it myApp and declared it within the main div (usually best placed in the body tag). Afterwards, establish a controller and utilize the scope module to initialize and utilize data as demonstrated above. This is the accompanying JavaScript code.

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

myApp.controller("TodoCtrl", function ($scope) {
    var that = $scope;

    $scope.poiType = 0;

    $scope.TYPE_POI = 0;
    $scope.TYPE_TRIP = 1;
    $scope.TYPE_WAYPOINT = 2;
    $scope.TYPE_EVENT = 3;

    $scope.popup = function () {
        alert(that.poiType);
    };
});

Live demo on jsfiddle

Answer №3

    <div class="btn-group btn-group-justified" 
             style="display: none;">

By adding style="display: none;", the radio buttons are hidden. Removing this will make them visible.

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

Tips for enhancing the presentation of JSON information

I recently ventured into the world of JSON and JS, managing to create a JSON file to showcase data using .onclick event. While I have successfully generated and displayed the JSON data on screen, my next goal is to present it in a table format for better c ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Leverage multiple services within a single AngularJS controller

Is it possible to use multiple services in the same controller? Currently, I am able to achieve this with different services, but it seems to only perform one service. <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs ...

The ng-repeat function is currently disabled and not displaying any data from the JSON object

I am currently facing an issue where the ng-repeat Directive in my code is getting commented out and not displaying the results of the JSON object. I have verified that the object is being properly passed to "this.paises2" using the toSource() method, and ...

Using a relative path in Ajax is ineffective

I am facing an unusual issue with AJAX. The HTML page I am working on is calling an AJAX function from this location: public_html/test/books.html The AJAX file that needs to be called is located here: public_html/lists/include/vote_up.php I have tried ...

A guide to checking an array of objects by their ID and assigning a new property using JavaScript

I am working with two arrays of objects called arr1 and arr2 If the ID in both arr1 and arr2 matches, I want to add the property names from arr1 to arr2 using JavaScript var arr1 = [ {id: 1, name : "Helena"}, {id: 2, name : "John"} ...

What is the relationship between ng-click and scope binding?

If my one-page website includes the following code: <div class="toolTile col-md-3"> <a ng-click="transId()" ng-href="{{ ppt.Globals.hasDebitCard ? '#/claimEnter' : '#/claimSub' }}"> <i ...

Get the @html.dropdownlistfor filtered for me

Currently, I am working on a project that requires me to filter the options in my second dropdown list based on the selection made in the first dropdown list. While the concept is clear, implementing it becomes tricky as I lack expertise in jQuery or JavaS ...

The initial number is inserted within the text box upon entering the final number

Whenever I enter the final digit, the text-box swallows up the initial number (it vanishes), resulting in an additional space. https://i.stack.imgur.com/Vfm8s.png https://i.stack.imgur.com/od4bQ.png Upon clicking outside of the text-box, the formatting ...

Is the JSON returned by the API server not being properly processed by the RequireJS module, resulting

After extensive research on promises and module creation, I am still unable to understand why my current setup is not functioning properly. My goal is to write a script that takes a username and then fetches user data from a 3rd party API using a separate ...

Obtain a byte array from an AngularJs controller

In my Angular controller, I am working with a byte array. When the download button is clicked in the view, I want to trigger the browser's download/saveAs dialog with 'report.pdf' as the pre-populated filename and PDF as the file type. After ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

Issues with ngresource failing to properly filter data when calling an oData based Rest Controller

My web API controller is built with MongoDb as the backend. public class NodesRestController : ApiController { private INodeService _nodeService; public NodesRestController(INodeService nodeService) { _nodeService = nodeService; ...

Employing an unchanging Map format for observation

I'm currently working on implementing a synchronization mechanism using observable and Map structures from Immutable.js. However, I'm encountering an issue where the Map is unable to function as an observable or perhaps I might be approaching it ...

Is it possible to invoke a Java Script function from a GridView using `<% Eval("") %>` as a parameter for the function?

Is there a way to call a javascript function with a single parameter from a link click within the GridView Control? I need to pass the value of the parameter using <%Eval("myfield")%>. How can this be accomplished? <ItemTemplate> ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...

Nuxt's dynamic route generation results in a 400 error status code

Currently integrating Nuxt with my app and aiming to establish a connection with my server to retrieve data. To create dynamic routes, I am utilizing the built-in generate method but facing some challenges. Upon executing the generate command, I encounte ...

attempting to merge two arrays into a single union

I am looking for a way to create a new array that contains only unique values from both the first and second arrays, maintaining their original order. This is my current approach: function union(first, second) { return first.filter(function(value) { ret ...

How to incorporate and separate JavaScript syntax for individual objects

Here is the data I have: const data = [ { date: '2018-04-11T00:00:00.000+07:00', price: 5000 }, { date: '2018-04-03T00:00:00.000+07:00', price: 2000 } ] I am attempting to incorporate moment.js syntax to format the date, ...

Is the promises functionality respected by the Nextjs API?

Greetings, I hope all is well with you. I am currently learning NEXTJS and working with its API, but I have encountered a problem. When I click too quickly, the promises seem to get stuck or encounter issues. You can see the tests in action in this brief 3 ...