angularjs checkbox Incorrect response in console - angularjs

I have two criteria:
1) Only allow one of two boxes selected at one time.
2) Capture the name of the box that is selected.
However, when I print out the list of checkbox objects they are correct, but when I check in the console they are not correct. For example,
HTML:
<div ng-repeat="treatment in treatment_list">
<input type="checkbox" value="{{treatment.name}}"
ng-model="treatment.checked"
ng-click="updateTreatment($index, treatment_list);
checkedTreatment(treatment_list)">
<label>Treatment {{treatment.name.toUpperCase()}}</label></input><br>
</div>
{{treatment_list}}
Controller:
$scope.treatment_list = [
{
name: 'a',
checked: false
}, {
name: 'b',
checked: false
}
];
$scope.updateTreatment = function(position, treatment_list) {
console.log(treatment_list);
angular.forEach(treatment_list, function(treatment, index) {
console.log(treatment.name, treatment.checked);
if (position != index) {
treatment.checked = false;
}
});
};
$scope.$watch('treatment.checked', function (treatment) {
console.log(treatment);
});
Plunker:
https://plnkr.co/edit/Hkb4IeKxi0TRqHRJA4JN?p=preview

Inorder to fullfill your requirement you should just use a radio box whith ng-model, it will work out of the box for you.

Use radio buttons instead:
angular.module("app",[])
.controller('ExampleController', function($scope) {
$scope.color = {
name: 'blue'
};
$scope.specialValue = {
"id": "12345",
"value": "green"
};
$scope.colorChange = function(color) {
console.log(color);
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<form name="myForm" ng-controller="ExampleController">
<label>
<input type="radio" ng-model="color.name" value="red"
ng-change="colorChange(color.name)" />
Red
</label><br/>
<label>
<input type="radio" ng-model="color.name" ng-value="specialValue"
ng-change="colorChange(color.name)" />
Green
</label><br/>
<label>
<input type="radio" ng-model="color.name" value="blue"
ng-change="colorChange(color.name)" />
Blue
</label><br/>
<tt>color = {{color.name | json}}</tt><br/>
</form>
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
</body>
For more infomation, see AngularJS input type=radio Directive API Reference

Related

Selected value in radio button group not retained in angularjs

I have radio button group in my angular page. Below is my code,
<span ng-repeat="radioButtonItem in radioButtonItem.Values">
<label class="radio-inline">
<input type="radio"
name="radioButtonName"
value="{{radioButtonItem.Id}}"
ng-model="radioButtonItem.SelectedValues"
ng-change="changeRadioButton()" />
{{radioButtonItem.Value}}
</label>
</span>
Ex :
Radio button 1 : .Male .Female
Radio button 2 : .ax .sy
Radio button 3 : .c .v
when i select the first group radio button say male and select the second group radio button say ax first
one is deselect(male). How to retain the values in radio button group?
Because your name is same for all the groups. Generate it dynamically too.
Here is how you could do it. I have attached an example too.
<input type="radio"
name="{{radioButtonItem.groupName}}"
value="{{radioButtonItem.Id}}"
ng-model="radioButtonItem.SelectedValues"
ng-change="changeRadioButton()"/>
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.cell = {
evaluator: "Guava2"
};
$scope.cell1 = {
evaluator: "Apple1"
};
$scope.evaluators = [{
name: "Guava1",
groupName: "guava"
}, {
name: "Guava2",
groupName: "guava"
}];
$scope.evaluators1 = [{
name: "Apple1",
groupName: "peachy"
}, {
name: "Peach2",
groupName: "peachy"
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html>
<body>
<div ng-app="myApp">
<div ng-controller="myController">
<div>Which one?</div>
<label class="radio" ng-repeat="eval in evaluators">
<input type="radio" ng-model="cell.evaluator" name="{{eval.groupName}}" value="{{eval.name}}">{{eval.name}}
</label>
<hr />
<div>You picked: {{cell.evaluator}}</div>
<br/>
<label class="radio" ng-repeat="eval in evaluators1">
<input type="radio" ng-model="cell1.evaluator" name="{{eval.groupName}}" value="{{eval.name}}">{{eval.name}}
</label>
<div>You picked: {{cell1.evaluator}}</div>
</div>
</div>
</body>
</html>

How to create a "other" or "catch all" radio button?

Suppose I want to present a few default options for the user but also want to allow them to enter their own value.
e.g.
Please select one of the following:
[ ] apple
[ ] pear
[ ] other: ___________
I want it so that if "other" is selected, then the input field that follows should be enabled and allow typing.
Html might look like this:
<input type="radio"
name="fruit"
ng-model="fruit"
value="apple"
> apple
<input type="radio"
name="fruit"
ng-model="fruit"
value="pear"
> pear
<input type="radio"
name="fruit"
ng-model="???"
value="???"
> Other:
<input type="text"
class="form-control"
ng-model="fruit"
ng-disabled="???">
What would you do here?
I had an implementation where the default options trigger an action on ng-change such that it changed a $scope.isOther to true, which would enable the input box and check the other radio box like so
<input type="radio"
name="fruit"
ng-model="fruit"
value="apple"
ng-change="isOther=true"
> apple
<input type="radio"
name="fruit"
ng-model="fruit"
value="pear"
ng-change="isOther=true"
> pear
<input type="radio"
name="fruit"
ng-model="isOther"
ng-change="fruit=null"
value="true"
> Other:
<input type="text"
class="form-control"
ng-model="fruit"
ng-disabled="!isOther">
That sort of works. But when I reload the page/data, if I have an "other" value entered, it doesn't know to automatically check "other", although my "other" value is in the input box. I could write some more code change the isOther value when I'm loading the data but I'm wondering if I'm even going about this the right way or whether there's a "catch all" that allows a radio box to be checked if it doesn't match any other values.
You can do it this way:
var myapp = angular.module('myApp', []);
myapp.controller('MyController', function($scope) {
$scope.fruits = ['apple', 'orange', 'plum', 'pear'];
$scope.fruit = {selectedOption: 'orange'};
$scope.isDisabled = function() {
if (_.contains($scope.fruits, $scope.fruit.selectedOption)) {
return true;
}
return false;
};
$scope.add = function() {
if($scope.x !== undefined && $scope.x !== '') {
$scope.fruits.push($scope.x);
$scope.fruit.selectedOption = $scope.x;
$scope.x = '';
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id='main' ng-app='myApp'>
<form name="myForm" ng-controller="MyController">
<div ng-repeat="f in fruits track by $index">
<input type="radio" name="fruit" ng-model="fruit.selectedOption" value={{f}}> {{f}}
</div>
<input type="radio" name="fruit" ng-model="fruit.selectedOption" value="other"> Other:
<input type="text" ng-model="x" ng-disabled="isDisabled()" ng-blur="add()">
<br> fruit = {{fruit.selectedOption}}
</form>
</div>
JSFiddle
I don't have a perfect answer, but I ended up doing it this way
html:
<div id='main' ng-app='myApp'>
<form name="myForm" ng-controller="MyController">
<div ng-repeat="f in fruits track by $index">
<input type="radio" name="fruit" ng-model="fruit.value" ng-value="f" ng-change="disableOther()"> {{f}}
</div>
<input type="radio" name="otherfruit" ng-change="fruit.value=null" ng-model="isOther" ng-value="true"> Other:
<input type="text" ng-model="fruit.value" ng-change="checkOther()" ng-class="{'disabled-input':isStandardFruit()}">
<br> fruit = {{fruit.value}}
</form>
</div>
code:
var myapp = angular.module('myApp', []);
myapp.controller('MyController', function($scope) {
$scope.fruits = ['apple', 'orange', 'plum', 'pear'];
$scope.fruit = {value:'orange'};
$scope.isStandardFruit = function() {
for(var i=0; i<$scope.fruits.length; i++) {
if( $scope.fruits[i] == $scope.fruit.value ) {
return true;
}
}
return false;
}
$scope.disableOther = function() {
$scope.isOther = false;
}
$scope.checkOther = function() {
if( !$scope.isStandardFruit() ) {
$scope.isOther = true;
}
}
});
JSFiddle
The one drawback is that if you type a standard fruit into the "other" input box, then it selects multiple radio buttons. I could uncheck the "other" button but then you couldn't type a fruit that contained the standard fruit as a prefix (e.g. you wouldn't be able to type "apple pear")
If anyone can come up with a better answer, I will change my vote and answers

How to change ng-model of a textbox on change of a radio value?

My textbox looks like this
<input type="number" ng-model="obj.celcius" min="0" max="100" >
I have two radio buttons
<input type="radio" ng-model="obj.selection" value="celcius">
<input type="radio" ng-model="obj.selection" value="farheneit">
When the user clicks on the farheneit radio button I want the ng-model of the textbox to change to obj.farheneit. How can I acheive this? I would also like to update min and max of the textbox.
try with obj[obj.selection].
refer below code snippet.
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.obj = {
selection: 'celcius',
celcius: 1,
farheneit: 2
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<input type="number" ng-model="obj[obj.selection]" min="0" max="100" >
<input type="radio" ng-model="obj.selection" value="celcius">
<input type="radio" ng-model="obj.selection" value="farheneit">
{{obj.selection}}
</div>
I have created the snippet below. For time being I have added random min and max values for Celsius and Fahrenheit.
var app = angular.module('app', []);
app.controller('test', function($scope) {
$scope.tempdata = {
"celsius": {
"min": 0,
"max": 100,
"value": 37
},
"fahrenheit": {
"min": 50,
"max": 150,
"value": 120
}
}
$scope.upDateData = function(data, type) {
$scope.obj.temp = data;
if (type == 'celsius') {
$scope.min = $scope.tempdata.celsius.min;
$scope.max = $scope.tempdata.celsius.max;
} else if (type == 'fahrenheit') {
$scope.min = $scope.tempdata.fahrenheit.min;
$scope.max = $scope.tempdata.fahrenheit.max;
}
}
});
.text-data {
width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<div ng-app="app" ng-controller="test">
Number:
<input type="number" class="text-data" ng-model="obj.temp" min="{{min}}" max="{{max}}">
<div>
Celsius:
<input type="radio" ng-model="obj.selection" ng-value="tempdata.celsius.value" ng-change="upDateData(obj.selection, 'celsius')"> Fahrenheit:
<input type="radio" ng-model="obj.selection" ng-value="tempdata.fahrenheit.value" ng-change="upDateData(obj.selection, 'fahrenheit')">
</div>
</div>

Is it possible to bind different values when selecting a radio button?

I have 2 radio buttons. I'd like to bind different attributes for each radio button. Eg:
<label>
Foo
<input type="radio" name="test" value="foo"/>
</label>
<label>
Bar
<input type="radio" name="test" value="bar"/>
</label>
radio foo has values "id" : "id1", "value" : "foo"
radio bar has values: "id" : "id2", "value" : "bar"
And the binding to a <p> should be something like:
<p>The id for selected radio is {{ radio.id }}, and value for it is {{ radio.value }}</p>
Resulting in "The id for selected radio is id1, and value for it is foo"
Yes. You can create an object for each radio button and assign id and value properties to the objects.
Example: https://jsfiddle.net/x9nfke0d/
Angular:
function Controller() {
var vm = this;
vm.selected_radio = null;
vm.foo = {
id: 1,
value: 'Foo'
};
vm.bar = {
id: 2,
value: 'Bar'
};
vm.setRadio = setRadio;
function setRadio(obj) {
vm.selected_radio = obj;
}
}
HTML:
<label>
Foo
<input type="radio" name="test" ng-click="ctrl.setRadio(ctrl.foo)">
</label>
<label>
Bar
<input type="radio" name="test" ng-click="ctrl.setRadio(ctrl.bar)">
</label>
You could go a step further and create an array of radio objects, then repeat them in a ng-repeat.
Working Fiddle Here
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
$scope.foo = {bar:"foo"};
}]);
<section ng-controller="MyCtrl">
{{foo.bar}}
<label>Foo<input ng-model="foo.bar" type="radio" name="test" value="foo"/></label>
<label>Bar<input ng-model="foo.bar" type="radio" name="test" value="bar"/></label>
</section>

How to pre-select radio buttons in angularjs

When my model value is true then I want the radio buttons to be selected when loaded, but its happening the otherway around. All false models are getting selected. How do fix this.
http://plnkr.co/edit/DIYm4vBM3srdS61K6EPA?p=preview
angular.module('radioExample', [])
.controller('ExampleController', ['$scope',
function($scope) {
$scope.kind = [{
name: 'task',
selected: false
}, {
name: 'bug',
selected: false
}, {
name: 'other',
selected: true
}, {
name: 'rfe',
selected: false
}]
$scope.$watch('kind', function() {
console.log('changed', JSON.stringify($scope.kind, null, 2))
}, true)
}
]);
use ng-value here is the doc for angular radio
<input type="radio" name="" id="" value="" ng-model="k.selected" ng-value="true" />
then, if the ng-value is true and the model value is also true then check box will checked
here is the update Demo
<input type="checkbox" id="rempass" ng-model="rememberMe" ng-checked="rememberMeUserInfoCheck()" > $scope.rememberMeUserInfoCheck=function() { return true; }
this works for me
Add ng-checked ="true" to your radio input field
`<input type="radio" ng-model="modelName" name="radioName" value="value1" ng-checked="true">`
I fixed the plunker plunker
<form name="myForm" ng-controller="ExampleController">
<br />all 'false' radio buttons are selected when 'value' is used -------------
<br />
<div ng-repeat="k in kind">
<input type="radio" name="" id="" value="" ng-model="!k.selected" value="k.selected" />{{k.name}}
</div>
<br />all radio buttons are selected when 'ng-value' is used -------------
<br />
<div ng-repeat="k in kind">
<input type="radio" name="" id="" value="" ng-model="k.selected" ng-value="k.selected" />{{k.name}}
</div>
</form>
you had it right.... just needed to add a ! so the model will take the opposite of the scope value... since you are using them for both I guess its wont hurt your code
For those working with FormGroup and FormControl:
In the template:
Add formControlName = sameNameforAllRadioButtonsOfAChoice as an attribute to your radio button input tags.
Also add value = "true" and value = "false" (you can also do it with numbers and strings, but I will continue with boolean).
In the component:
Add the name, e.g. sameNameforAllRadioButtonsOfAChoice, to your FormGroup:
myForm = new FormGroup({sameNameforAllRadioButtonsOfAChoice: new FormControl('false')})
This sets the default value to false. In the FormControl, be careful to write it as a string!
BONUS - If you need Validation:
import { FormControl, FormGroup, Validators } from '#angular/forms';
myForm = new FormGroup({sameNameforAllRadioButtonsOfAChoice: new FormControl('false', [Validators.required])})

Resources