NG-model and NG-value resulted in the incorrect radio input being checked upon loading

Here is a simple example of a form with radio inputs. Check out the DEMO on PLNKR:

<form class="some-inputs">
    <div ng-repeat="da in data">
      <span>{{$index}}: {{da}}</span>
      <label>
        <input type="radio" id="lock-{{$index}}"
               name="lock-choice-{{$index}}"
               ng-model="mdl['account-{{$index}}']['blocked']"
               ng-value="da.blocked">
        <span>blocked</span>
      </label>
      <label>
        <input type="radio" id="unrealized-{{$index}}"
               name="lock-choice-{{$index}}"
               ng-model="mdl['account-{{$index}}']['unrealized']"
               ng-value="da.unrealized">
        <span>not blocked</span>
      </label>
    </div>
</form>

In this example, I'm using ng-model and ng-value instead of ng-checked. The objects with properties are printed for comparison purposes.

My question is why, in each example, the second radio button is always checked even if its value is false. The first radio, which has a truthy value, should be checked instead. Why does this happen?

When I remove the ng-value attributes from the input elements, none of the radios are checked, even though the ng-model properties already have values that could determine their checked state.

Answer №1

For a clearer representation when using ng-repeat with objects, utilize (key, value) as the iterator:

<div ng-repeat="(key,da) in data">

This approach enhances the readability of the HTML code.

Check Out the DEMO

angular.module('app', [])
.controller('ctrl', function($scope) {
  $scope.data = {
    "account-0":{
      "blocked":true,
    },
    "account-1":{
      "blocked":false,
    },
    "account-2":{
      "blocked":false,
    },
    "account-3":{
      "blocked":true,
    }
  };
  $scope.mdl = {};
  angular.forEach($scope.data, (value, key)=> {
    $scope.mdl[key] = {choice: value.blocked?'blocked':'not blocked'};
  });
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
  <form name="form1">
    <div ng-repeat="(key, da) in data">
      <span>{{key}}</span>
      <label>
        <input type="radio" id="{{key}}-blocked"
               name="block-choice-{{key}}"
               ng-model="mdl[key].choice"
               ng-value="'blocked'">
        <span>blocked</span>
      </label>
      <label>
        <input type="radio" id="{{key}}-not-blocked"
               name="block-choice-{{key}}" 
               ng-model="mdl[key].choice"
               ng-value="'not blocked'">
        <span>not blocked</span>
      </label>
      <label>
        <input type="radio" id="{{key}}-undecided"
               name="block-choice-{{key}}" 
               ng-model="mdl[key].choice"
               ng-value="'undecided'">
        <span>undecided</span>
      </label>
    </div>
    <hr>
    <div ng-repeat="(k,v) in mdl">
    {{k}} {{v}}
    </div>
  </form>
</body>

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

utilizing AJAX to retrieve scripts from WITHIN my own domain

In the realm of ajax scripts, I encounter a scenario where referencing something within the same domain requires passing HTML and associated javascript. Due to it being a non X-domain setup, I anticipate that this could be achievable. The aim here is to fe ...

Encountered an issue resolving the module specifier "stimulus-autocomplete"

Ruby 3.0.3 Rails 7.0.0.alpha2 Upon completing the steps for installation and usage, I started the server only to encounter the following error message: Uncaught TypeError: Failed to resolve module specifier "stimulus-autocomplete". Relative refe ...

How do I change the 'CSS Theme' of my website?

With Halloween approaching, I am eager to transform my website's BODY css into a spooky Halloween theme. The challenge is that my .Net pages are Templates. Is there a way for me to ensure that the body class checks for an existing CSS theme override? ...

After logging in successfully, the React app needs a hard refresh to update the

I'm encountering a debugging challenge and would appreciate any assistance from the community. I've been working on my first React app and successfully implemented a Login feature, but after a user logs in, they have to hard refresh their browser ...

Modifying an @Input element within a component does not result in any changes being reflected in the parent component

Here is the scenario with my component: @Component({ selector: 'child' }) export class ChildComponent { @Input() childObject: ChildObject; changeObject(newObject: ChildObject){ childObject = newObject; } } After calling ...

What is the significance of using the variable name "$scope" in coding?

As a newcomer to Javascript, I recently finished reading the book Eloquent Javascript and am now delving into AngularJS from O'Reilly. While working on a code snippet provided in the AngularJS book, I encountered hours of frustration trying to figure ...

converting time stamps to written text

Is there a JavaScript library available that can convert a timestamp (Date Java class value) to text? For example: Just two minutes ago 4 hours back 23 August 2009 Does such a library exist? If not, I'll take on the challenge of implementing it ...

Issue: Attempting to write data after reaching the end in Node.js while using

I have encountered the following error: Heading Caught exception: Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15) at ServerResponse.res.write (/home/projectfolder/node_modules/express/node_modules/connect/lib/mid ...

Utilizing module pattern in JavaScript to reveal computed knockout settings

I've encountered an issue while using knockout with the revealing module pattern. My goal is to pass an observable by reference and have its value based on a computed function. However, it seems like the observable is being passed in by value instead ...

Modify the array value and access it outside of an asynchronous function

Is there a way to set values in an array from an asynchronous function and access it outside of that function's scope? I am working on a project where I need to randomize values in an array, so that I can assign images randomly to different div eleme ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Obtain the reference to the $scope variable in Angular from a select element

I am faced with a challenge: $scope.selectlist = ["list1","list2","list3"]; Once I select an item, I want to display the corresponding list based on the selected value. The lists available in my scope are : $scope.list1 $scope.list2 $scope.list3 How c ...

Ways to elegantly re-establish a websocket connection?

I've been working on a single-page application that utilizes HTTP and Websockets. When the user submits a form, I start streaming a response back to the client. Here's a snippet of the client-side code: var html = `<!DOCTYPE html> <met ...

Tips for displaying an edit action icon when hovering over specific text

Looking for a way to display or hide the edit icon when hovering over specific text? Take a look at this snippet of HTML code: <ul> <li> <a id="pop" href="javascript:;;" data-content="test Desc" data-id="123"> &l ...

Animate the entire paragraph with CSS hover effect

I'm seeking ideas on how to achieve a specific effect without the need to wrap individual lines in inner elements like span or a. Check out this example <div class="m-linkitem"> <h1>Hover Below</h1> <a href="#">Lorem ...

How can you modify a hyperlink URL before it is activated?

I'm facing an issue with a URL structure that needs updating before it is clicked. The current URL looks like this: https://url.com/a b c which is causing redirection problems because the actual link has underscores instead of spaces in its URL. Is ...

Checking the Value of the Second Child Element Using jQuery

I am struggling with a DIV structure that looks like this: <div class="metafield_table"> <div class="metafield"></div> <div class="metafield"></div> <div class="metafield"> ...

"Using Js-ctypes to interface with a third-party DLL that returns a string

I have encountered an issue while working with a DLL using js-ctypes, which is written in C. After calling the method that returns a string and trying to access the content of the pointer, Firefox crashes! The following code snippet works perfectly: Fun ...

The menu header is experiencing issues with alignment

I've been tackling the alignment of elements in my menu header, but for some reason, they're not lining up horizontally as intended. Instead, they are stacked below each other. Here's the link to my jsfiddle Here's a snippet of my HTML ...

Modify the Google Translate dropdown using programming techniques

Recently, I attempted to integrate the Google Translate dropdown feature into a website using the following code snippet: function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google ...