Angularjs default value of radio button is not working - angularjs

I'm new here and this is my first post. Please let me know if I do anything wrong, thanks.
Recently I'm working on an account management page using angularjs. I'm having a problem when setting default checked to gender radio buttons. I use bit in database to record gender and yes I've tried ng-value but it doesn't work. Here is my code:
var module = angular.module("MainApp", []);
module.controller('GlobalCtrl',
function ($scope, $http) {
$scope.testerSet = [{ name: 'Ysoda', Gender: true, age: 9 }, { name: 'Lydia', Gender: false, age: 9 }];
$scope.setCurrentTester = function () {
if ($scope.testerCollection[0] != null) {
$scope.currentTester = $scope.testerCollection[0];
// $scope.$apply();
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='MainApp'>
<div ng-controller='GlobalCtrl'>
{{testerSet[0].name}}
<select multiple ng-model="testerCollection" style="width: 100%; height: 400px" ng-options="tester.name for tester in testerSet" ng-change="setCurrentTester();">
</select>
<div>
<label>Gender:</label>
{{currentTester.name}}
{{currentTester.Gender}}
<label><input type="radio" runat="server" name="genderSet" ng-model="currentTester.Gender" ng-value=true id="radioMale" /> Male</label>
<label><input type="radio" runat="server" name="genderSet" ng-model="currentTester.Gender" ng-value=false id="radioFemale" /> Female</label>
</div>
</div>
</div>
I use multiple select to show a select as a listbox, I'm thinking that might be the reason why it doesn't work. I've spent hours working on this little button and I just don't know why names and account and all other data work well but the gender radio boxes do not.
I use {{currentUser.Gender}} to check value and the value shows correct. However, the default check still doesn't work.
Thank you for your time.

<input type="radio" runat="server" name="genderSet" ng-model="currentUser.Gender" ng-value=true id="radioMale" /> Male
ng-value="true" give the value without quotes ng-value=true

Related

Function to add and show up a new object in an array

I just got started with playing around with AngularJS and I would like to build an app, that just adds another person´s name and his/her date of birth.
I have got already initial data (2 persons and their date of birth (dob).
By writing down the full name and dob and then pressing the add button, I would like to have another person added as well as his/her dob - and this new person should be also listed and visible in the list.
So far I made it that the function creates a new object. But unfortunately I am not able to combine the input data with the new added object in a proper way.
Can somebody help me? Maybe there is an easier way to do it
So far I created this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myBirthApp",[]);
app.controller("myCtrl", function($scope){
$scope.birthdays=[
{fullName:'Jane Doe', dateOfBirth:'08.03.1990'},
{fullName:'John Doe', dateOfBirth:'19.11.1995'}];
// create new array with addItem!
$scope.addItem = function () {
$scope.birthdays.push($scope.addMe);
}
});
</script>
<div ng-app="myBirthApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in birthdays"><p>Name: {{x.fullName}}</p> <p>Date of birth: {{x.dateOfBirth}}</p> </br></li>
</ul>
<form>
<fieldset>
<legend>Add a person</legend>
First name and last name: <input type="text" ng-model="fullName"></br>
Date of birth: <input type="date" ng-model="dateOfBirth"></br>
<button ng-click="addItem()">Add</button>
</fieldset>
</form>
</div>
</body>
</html>
You could declare a variable:
$scope.person = {
fullName: '',
dateOfBirth: null
};
and bind it to ngModel inputs:
<input type="text" ng-model="person.fullName"><br />
<input type="date" ng-model="person.dateOfBirth">
and then in addItem method push it to birthdays array. (Of course it needs further additions, validation checks etc but this is the basic idea)
Check here a working demo: DEMO

Radio button and custom values in Angular JS [duplicate]

Using AngularJS, I would like to create a list of options with radio buttons, the last of which has an empty text field labeled 'Other' for inputing an option that is not in the list. Here's a demonstration of what I have in mind that I bootstrapped in CodePen. Since Stack Overflow insists on including CodePen code in this message, here it is:
js:
angular.module('choices', [])
.controller("MainCtrl", ['$scope', function($scope) {
$scope.color = '';
$scope.colors = [
"Red",
"Green",
"Blue",
"Other"
];
$scope.changeColor = function(){
$scope.color = "Red"
};
}]);
html:
<html>
<head>
<body ng-app="choices" ng-controller="MainCtrl">
<div ng-repeat="color in colors">
<input type="radio" ng-model="$parent.color" ng-value="color" id="{{color}}" name="color">
<label>
{{color}}
</label>
<input type="text" ng-model="$parent.color" ng-show="color=='Other'">
</div>
<p></p>
The chosen color is <strong>{{color}}</strong>
<p></p>
<button ng-click="changeColor()">Change color</button>
</body>
</html>
Here is what I want this demo app to do:
When I choose any option except for Other, the text field should remain blank;
If I place cursor in the text field, the option Other should be selected
Once I start typing in the text field, the option Other should remain selected
If I change the model that registers the options (in the demo app achieved by clicking the Change color button), the corresponding radio button should be selected.
I achieved most of that functionality by using three models (one for color, one for keeping track of radio buttons and one for the Other field) and three watchers, but the resultant app seems brittle and fails some of the tests. Could you please suggest a better way for creating such a selector in Angular using as few models and watchers as possible?
(My question is somewhat similar to this SO question, but I hope is different enough not to be considered a duplicate.)
Add a separate scope property for the other text:
$scope.other = '';
Add a colorChanged() method which will be called when the color is changed. This will set the other text to empty if color is not 'Other':
$scope.colorChanged = function () {
if ($scope.color != 'Other') {
$scope.other = '';
}
};
This will also need to be called from changeColor(). I ended up changing changeColor to allow the color to be passed in. It otherwise defaults to red:
$scope.changeColor = function(color){
$scope.color = color || "Red";
$scope.colorChanged();
};
Add ng-change="colorChanged()" to radio button:
<input type="radio" ng-model="$parent.color" ng-value="color" id="{{color}}" name="color" ng-change="colorChanged()">
Change the textbox to use other as the model. Use ng-focus to detect when textbox is focused and then set color to 'Other'. Doing this will select the radio button.
<input type="text" ng-model="$parent.other" ng-show="color=='Other'" ng-focus="$parent.color = 'Other'"/>
Update the display of the color to show the other text:
The chosen color is <strong>{{color}}<span ng-if="color === 'Other' && other != ''"> - {{other}}</span></strong>
Plunkr
I made some very small modifications to your pen HERE.
The short of it is, instead of having 'Other' as a value, i made it a blank option, with the input actually controlling the value.
$scope.colors = [
"Red",
"Green",
"Blue",
""
];
html:
<label >
{{color || 'Other'}}
</label>
<input type="text" ng-model="$parent.color" ng-show="color==''">
This allows the input to actually control the value of 'Other'...

when selecting one option in radio buttons group, display some info and make sums of selected items

I'm tring to build a sort of web based pricelist for the company where i work, I'll post the $scope.model = ''; example of the work I'm doing what i want to achieve is when a person select one option in the radio buttons group i want to display some info and make sums of the selected items, the other thing i want to reach is to enable the radio buttons groups only if the previous is selected.
I would suggest writing an onChange function which is then fired each time a button is pressed. This onChange function should read the values of all the currently selected buttons and then you can manipulate them as you need (add them etc).
To achieve this you will probably want to convert your buttons from label to input, or give your label a hidden input which stores the currently selected value.
Here I Created one jsfiddle according for your need. Here I have one Array of element and I bind this in HTML page.
<div ng-app="">
<div ng-controller="MyCtrl">
<label data-ng-repeat="choice in amountList.choices">
<input type="radio" name="response" data-ng-model="price" data-ng-value="true" ng-change="FirstListSelect(choice)" />
{{choice.price}}
</label>
<div>
<label data-ng-repeat="choice in amountList.choices">
<input type="radio" name="response2" data-ng-model="price2" data-ng-value="true" ng-change="SecondListSelect(choice)" />
{{choice.price}}
</label>
</div>
<br/>
{{total}}
</div>
</div>
And I had done some code into Js file :-
function MyCtrl($scope) {
$scope.FirstListvalue=0;
$scope.SecondListvalue=0;
$scope.total=0;
$scope.amountList = {
choices: [{
id: 1,
price: 500
}, {
id: 2,
price: 600
}, {
id: 3,
price: 500
}]
};
$scope.FirstListSelect=function(data)
{
alert(data.price);
$scope.FistListvalue=data.price;
if($scope.SecondListvalue!=null)
{
$scope.total=data.price+$scope.SecondListvalue;
}
else
{
$scope.total=data.price;
}
};
$scope.SecondListSelect=function(data)
{
alert(data.id);
$scope.SecondListvalue=data.price
if($scope.FistListvalue!=null)
{
$scope.total=data.price+$scope.FistListvalue;
}
else
{
$scope.total=data.price;
}
};
}
Following working example I created :- http://jsfiddle.net/kpsingh/LXAt7/503/

How to set radio button in angularjs with Object

I have created radio buttons in angularjs using array of objects using ng-value and ng-model.
`
<div ng-controller="DemoController">
<div ng-repeat="detail in details">
<input type="radio" ng-model="$parent.selectedVal" ng-value="detail" name="test">
</div>
{{selectedVal}}
</div>
`
On selection of radio button model is populated with corresponding object value. But I am not sure how to initialize it using controller with object.
var app = angular.module('myApp', []);
app.controller("DemoController",DemoController);
function DemoController($scope) {
$scope.selectedVal={name:"Def",age:4} ;
$scope.details=[{name:'Abc',age:2},{name:'Xyz',age:3},{name:'Def',age:4}];
}
You should reference the selected value from the details array instead of creating a new instance:
$scope.details = [{ name:'Abc', age:2 }, { name:'Xyz', age:3 }, { name:'Def', age:4 }];
$scope.selectedVal = $scope.details[2];
This will select the last of the 3 radio buttons. Also if both details and selectedVal are defined within the same scope you should update your radio button as well, it's quite unclear why you referenced selectedVal from a $parentScope:
<input type="radio" ng-model="selectedVal" ng-value="detail" name="test" />
And here's the updated fiddle: https://jsfiddle.net/sb3krc8c/2/

Reset select to default value with AngularJS

I have a following question for AngularJS. I have a
select with options created with ngOptions. I want to
set selected option back to default option. I tried to
delete model variable e.g:
if(angular.isDefined($scope.first)){
delete $scope.first;
}
But this not working. Here is my html.
<div ng-app="app">
<div ng-controller="testCtrl">
<select data-ng-model="first" data-ng-options="item.name for item in selectContent" required="required">
<option value="" style="display: none;">-- select --</option>
</select>
{{first.value}}
<hr/>
<input type="button" value="reset dropdown" data-ng-click="resetDropDown()"/>
</div>
</div>
And here is my JavaScript code:
angular.module('app', []).controller('testCtrl', function ($scope) {
$scope.selectContent = [
{
name: "first",
value: "1"
},
{
name: "second",
value: "2"
}
];
$scope.resetDropDown = function() {
if(angular.isDefined($scope.first)){
delete $scope.first;
}
}
});
Here is working jsfiddle:
http://jsfiddle.net/zono/rzJ2w/
How I can solve this problem?
Best regards.
Your reset-button is placed outside of the div containing your controller. This means that your reset-function does not exist in the context where you try to use it.
Change to:
<div ng-app="app">
<div ng-controller="testCtrl">
<select data-ng-model="first" data-ng-options="item.name for item in selectContent" required="required">
<option value="" style="display: none;">-- select --</option>
</select>
{{first.value}}
<hr/>
<input type="button" value="reset dropdown" data-ng-click="resetDropDown()"/>
</div>
</div>
It's always a good idea to use a debugger to make sure the code you're trying to fix is actually being executed.
$scope.resetDropDown = function() {
$scope.first = "";
}
Solution above works for Windows and Android, but did not work for iOS browsers. Probably events are happening in different order there.
So for my code I:
created ID for select element, so I could easily find it by
iQuery;
created delayed invocation of to statements to ensure the
reset is happenning at the very end;
and just in case was
resetting in two ways (but just first way was actually enough in iOS
too);
function resetDropDown () {
$timeout(function(){
$scope.first = '';
// jQuery way
$('select#idOfSelectElement option:first' ).prop( 'selected', true );
}, 200);
}

Resources