Choosing the initial option in an AngularJS radio button

I need to set the default selected value of a radio button to 3. The code I am using is:

<div class="checkbox-group" ng-init="ac.ServiceCode=3">

                <input type="radio" ng-model="ac.ServiceCode" id="acuOne" value="1" ng-change='GetAcuityLevel(1)'>
                <label for="acuityone">1</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuTwo" value="2" ng-change='GetAcuityLevel(2)'>
                 <label for="acuitytwo">2</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuThree" value="3" ng-change='GetAcuityLevel(3)'>
                 <label for="acuitythree">3</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuFour" value="4" ng-change='GetAcuityLevel(4)'>
                 <label for="acuityfour">4</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuFive" value="5" ng-change='GetAcuityLevel(5)'>
                 <label for="acuityfive">5</label>

</div>

However, it always displays the value 3 as selected. When I remove the above code, it correctly shows the selected value in the radio button. My goal is to have the radio buttons pre-select a value if the service returns a value between 1 and 5, otherwise default to 3.

Answer №1

The reason for this behavior is due to the presence of an ng-init directive that automatically assigns a value.

ng-init="ac.ServiceCode=3"

By using this approach, the default value will always be set to 3 upon initialization.

To manage ac.ServiceCode differently, especially if your service involves an $http.get request:

        $http.get('api/myservice').
            success(function(data, status, headers, config) {
                 if(data.valueReturned != null)
                    $scope.ac.ServiceCode = data.valueReturned;
                 else
                    $scope.ac.ServiceCode = 3;
            });
    };

In essence, it's advisable to handle the default value logic within your service rather than in the HTML markup.

Answer №2

Consider trying this modification:

<div class="checkbox-group" ng-init="ac.ServiceCode = 3">

Instead of the original code above, try using:

<div class="checkbox-group" ng-init="ac.ServiceCode = ac.ServiceCode ? ac.ServiceCode : 3">

This utilizes a ternary operator to verify the value's truthiness and assigns it to 3 if it is not.

Answer №3

To resolve the issue, avoid using ng-init and utilize ng-if instead. This will ensure that the appropriate value is selected when the service returns values, otherwise 3 will be selected.

Make a change like this: $scope.ac = {}; becomes $scope.ac = { ServiceCode:4} and observe the behavior.

var app = angular.module('myapp',[]);

app.controller('appCtrl',function($scope){
  
  $scope.ac = {};
  
    
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="appCtrl">
  <div class="checkbox-group" ng-if="!(ac.ServiceCode)?ac.ServiceCode=3:ac.ServiceCode">
    <input type="radio" ng-model="ac.ServiceCode" id="acuOne" value="1" ng-change='GetAcuityLevel(1)'>
                <label for="acuityone">1</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuTwo" value="2" ng-change='GetAcuityLevel(2)'>
                 <label for="acuitytwo">2</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuThree" value="3" ng-change='GetAcuityLevel(3)'>
                 <label for="acuitythree">3</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuFour" value="4" ng-change='GetAcuityLevel(4)'>
                 <label for="acuityfour">4</label>

                 <input type="radio" ng-model="ac.ServiceCode" id="acuFive" value="5" ng-change='GetAcuityLevel(5)'>
                 <label for="acuityfive">5</label>

  </div>
</div>  

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

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

How can we implement the json() method on a promise result that may be either a Response or void in Typescript?

When working on my React Native app, I encountered an issue with making an API call and using the json() method on the result. Here is the code snippet: await fetch(...) .catch(e => {...}) .then(res => res.json().then(...) An error was thrown by ...

Having some trouble with node.js and the fs module when checking if a file exists. Let

I'm a bit confused about the various methods in Node.js to check if a file exists using fs(). One option is to use fs.readFile(): fs.readFile('somefile.html', function (err, data) { if (err) { /* file doesn't exist */ } else { /* ...

Evaluating Angular directive scopes through function binding (&)

Currently, we are encountering some unusual behavior regarding the binding of a function to a directive scope. Check out an example on JSBin. Here's the scenario - we have a directive with a scope object structured like this: scope: { fn: '& ...

What is the method to activate the ability to select multiple rows in an AngularJS

I have created an HTML table and used ng-repeat to display items in the table. However, I am unable to select multiple rows in the table. How can I achieve this using the control key? Thank you! <div class="table_bg"> <table datatable="ng" dt-opt ...

Is it possible to utilize AngularJS ngAnimate to perform cross-fading transitions on list items?

I am currently exploring the ins and outs of angularJS with my simple message ticker example. This ticker displays messages by toggling the CSS display property of one of the li elements. <div id="ngtickerMessage" class="ngtickerMessage"> ...

Encountering the "React Hook useEffect missing dependency" warning for a state variable that does not actually need to be included in the dependency array

My eslint is throwing an error for react-hooks/exhaustive-deps. I believe my code is correct as the function should only execute when there is a change in the pathname: const pathname = usePathname(); useEffect(() => { setNavigation( navig ...

External variable accessing the getjson function

I have a question about optimizing the usage of the title variable within the getJSON function. Here's a sample code snippet that I'm working with: for (var x = 0; x < temp_addresses.length; x++) { var title = temp_addresses[x].title; ...

Transforming a menu tab into an active anchor when navigating to a particular section

Hello, I have successfully created a JavaScript code that can dynamically add menu tabs into the menu list window.addEventListener("load", () => { const navList = document.getElementById("nav_list") const fragment ...

What is the best method for updating inner html with AJAX using the results obtained from json_encode?

If you need further clarification on how this works, feel free to check out this fiddle for a demonstration. In my setup, I have multiple DIVs each with a unique ID such as desk_85 (the number changes accordingly). <div class="desk_box_ver id="desk_8 ...

What could be causing the Metamask account address to return as undefined even after it was stored in the useState() function?

A code snippet I have establishes a connection to the Metamask wallet and initializes the account address using useState() hook. const [currentAccount, setCurrentAccount] = useState("") const connectWallet = async () => { try { if (! ...

Creating Angular UI states with parameters in TypeScript

My Understanding In my experience with TypeScript and angular's ui state, I have utilized "type assertion" through the UI-Router definitely typed library. By injecting $state into my code as shown below: function myCtrl($state: ng.ui.IStateService){ ...

Send the form using an alternative method to avoid using preventDefault

Having some trouble with my website's sign-in functionality not working properly on all browsers. In Firefox, I keep getting a "ReferenceError: event is not defined" error. I've read through various posts about preventDefault behaving differentl ...

How can I fix my HTML Image input not redirecting when clicked?

I have successfully implemented the following code: <input type="button" name="btnHello" value="Hello" onclick="Test();"/> Here is the JS function that accompanies it: function Test() { window.location.href = "Page2.aspx"; } Initially, clicking ...

The error message states that the object function defined as `(req, res, next) { app.handle(req, res, next); }` does not contain the method 'configure'

Could somebody help me understand why I encounter this error when attempting to execute the code below? var express = require('express'); var login = require('./routes/login'); var app = express(); //all configurations app.confi ...

Using values across different Express routes in Node.jsIn Node.js development,

I'm a beginner with Express and working on a Node.js application. I'm facing an issue with using the same parameters in my code: app.get('/signin', function (req, res) { renderView(req, res, 'signin.jade'); }); app.get(&ap ...

Creating elegant Select Dropdown Box in AngularJS without relying on images

I am currently working on an angular page and have implemented a dropdown with ng-Options to fetch and set values successfully. However, I am now looking to enhance the appearance of this dropdown. After exploring options like ui-select, I realized that be ...

Is it acceptable to employ async: false when requesting small amounts of data?

I am curious about the best practices for retrieving small data from the server. One example is using an ajax (or sjax) call to check for new notifications for a user. function checkNewNotifs() { $.ajax({ url: '/Home/CheckNewN ...

Using Selenium 2 to dynamically insert CSS styles into the currently visible webpage

I experimented with using jQuery on a webpage that has already been modified by jQuery in order to add custom CSS code: jQuery('head').append('<style type=\"text/css\">body { background: #000; }</style>'); When I ...

How can I utilize the LED flash on a Windows Phone using WinJS?

Currently delving into the world of WinJS and endeavoring to create an application that involves operating the LED Flash. I am seeking guidance on how to properly access the LED Flash functionality to allow for toggling it ON or OFF. Your insights on how ...