How to check a radio button with angularJS? - javascript

I am creating a html / angularjs form. In the form i have a radio button with yes or no. So i want to check by default the button No.
This is the code i use :
My controller :
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.myvariable = 'false';
}]);
My html code snippet:
<div class="col-lg-10">
<input type="radio" id="variable" name="variable" ng-model="myvariable" value="true">Yes</input>
<input type="radio" id="variable" name="variable" ng-model="myvariable" value="false">No</input>
</div>
But nothing is selected(checked) when i load the form the first time. I have to click to one value to have one selected (checked)
What's wrong with my code ? Here the plunker link
Thanks

I've made a fiddle for you. Check HERE
You should also set ng-value which should be true or false
<div ng-controller="MyCtrl">
<div ng-repeat="o in options">
<input type="radio" name="group1" ng-model="o.checked" ng-value="o.checked"></input>
<label>{{o.name}}</label>
</div>
</div>
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.options = [
{ name: 'OPT1', id: 1, checked: false },
{ name: 'OPT2',id: 2, checked: false },
{ name: 'OPT3',id: 3, checked: true }
];
}

The reason why it does not work in your plunkr is because you create a module named "radioExample" but you don't use it when you write the HTML code.
Basically, replace this -
<html ng-app>
at the beginning of the code with this
<html ng-app="radioExample">
This way, when you declare the controller, AngularJS knows which module it needs to look into to get the controller.
Note - if you had not associated your controller with a module, then your code would work.

Check out ng-checked. What you have to do is to add ng-app="radioExample" to the html-Tag of your Application.
Then add ng-checked="myvariable == 'false'" and ng-value="'value'" like in the following plunker example:
Plunker
<div class="col-lg-10">
<input ng-checked="myvariable == 'true'" type="radio" id="variable" name="variable" ng-model="myvariable" value="true">Yes
<input ng-checked="myvariable == 'false'" type="radio" id="variable" name="variable" ng-model="myvariable" value="false">No
</div>

Error in data binding. Define myvariable in controller override value in radiobutton. You must use ng-repeat like
<div ng-repeat="o in options">
<input type="radio" name="name" ng-model="o.checked" ng-value="o.checked"></input>
<label>{{o.name}}</label>
</div>
(I use code from previous answer)

Related

How to pass index value to controller from ng-repeat in Angular

I am dynamically creating divs, while clicking a button which contains some radio inputs. In the controller I have an array for the divs population which initially has a length of 1.
'use strict';
angular.module('load').controller(
'commodityController',
function($scope, $http, $state, $stateParams) {
$scope.parentload = $scope.$parent.load;
$scope.addMoreCommodities = function() {
$scope.parentload.loadCommodities.push({
'isHazmat' : false,
'dimension' : 'IN'
});
}
$scope.parentload.loadCommodities = []; // emtry array
$scope.addMoreCommodities(); // Here initialize the array
$scope.changeHazmat = function(booleans, val) {
console.log("booleans " + booleans);
console.log("isactive " + val);
$scope.parentload.loadCommodities[val].isHazmat = booleans;
};
});
Using following html, while loading the page div populated well,
<div class="form-right-card disabledInput" ng-init="showname==true" id="commodityContent">
<form name="commodityAttForm">
<div ng-repeat="loadCommodities in load.loadCommodities">
<div class="form-group33"> {{$index}} // here value prints correctly
<label class="form-label">Hazmat</label>
<input type="radio" class="form-btn-inactive" ng-click="changeHazmat('true',$index)" id="yes" name="hazmat" />
<label class="plsLabel" for="yes">Yes</label>
<input type="radio" class="form-btn-inactive" ng-click="changeHazmat('false',$index)" id="no" name="hazmat" />
<label class="plsLabel" for="no">No</label>
</div>
</div>
</form>
</div>
<button class="form-btn-link" ng-click="addMoreCommodities()">+ Add Commodity</button>
I am able to generate the div with all the inputs when clicking on the button. Problem is, I am sending the $index to controller on ng-click of the radio buttons, while clicking on the radio buttons, I am calling the function changeHazmat('true',$index) here the index is always 0, even when I have an array with a length greater than 1.
$scope.changeHazmat = function(selected, val) {
console.log("val" + val);
$scope.parentload.loadCommodities[val].isHazmat = selected;
Log is always printing the index as 0.
Can someone help me here, what am I doing wrong?
You are correctly passing the $index the controller and the code should work.
However I would recommend to use ngModel with ngValue directive.
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=true name="hazmat" />
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope', function($scope, ) {
$scope.parentload = {
loadCommodities: []
};
$scope.addMoreCommodities = function() {
$scope.parentload.loadCommodities.push({
'isHazmat': false,
'dimension': 'IN'
});
}
$scope.addMoreCommodities();
$scope.changeHazmat = function(booleans, val) {
$scope.parentload.loadCommodities[val].isHazmat = booleans;
};
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="Controller">
<div ng-repeat="loadCommodities in parentload.loadCommodities">
<div class="form-group33">
<label class="form-label">Hazmat</label>
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=true name="hazmat" />
<label class="plsLabel" for="yes">Yes</label>
<input type="radio" ng-model="loadCommodities.isHazmat" ng-value=false name="hazmat" />
<label class="plsLabel" for="no">No</label>
</div>
<p>{{parentload.loadCommodities}}</p>
</div>
</div>
</div>
I'm wondering if the problem is you're assigning the same "id" ('yes' and 'no') to multiple divs (ie inside the loop). It might be the reason the $index isn't working for you. If you remove the id's for the time being and re-try, I'm thinking the problem goes away.

Make checkbox not clickable in Angular

I have a checkbox which I want to make not clickable. But it also has ng-click function attached. How to do this ?
<input id="record-2" type="checkbox" class="checkbox" ng-click="doIfChecked()">
I tried adding ng-readonly, ng-disabled but it did not work. I added css pointer-events: none but it did not work. I want this checkbox to be not clickable on boolean true/false expression. any idea?
Can you handle the condition of non-clickability inside the ng-click function? If not then:
<input ng-disabled="disableCondition" id="record-2" type="checkbox" class="checkbox" ng-click="disableCondition?(return false):doIfChecked()">
Something like above should work for you.
Explanation:
If you know the condition to disable the input, then use the same condition to conditionally call the function or return false on click. Same logic can be handled in the ng-click handler too.
Here is a working sinppet
var app = angular.module("myApp", [])
app.controller("mainController", ["$scope", function($scope){
$scope.someFlag=false;
$scope.doIfChecked= function(){
$scope.someFlag=true;
}
}]);
select{
width:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<input id="record-2" ng-controller="mainController" type="checkbox" ng-controller="mainController" class="checkbox" ng-disabled="someFlag" ng-click="doIfChecked()">
</body>

$event not defined in ng-change on text input

I hope my issue is simple to solve, I can't access the value by ng-model because i have multiple of these boxes as they are rendered as part of a list of inputs in a form. I am trying to get the ID and text value of a text box with ng-change. heres my html:
<input type="text" class="other-box" ng-model="test" id="4" ng-change="otherBoxUpdate(this)"/>
(ng-model is required, which is why it's in there). Hers is my controller snippet:
$scope.otherBoxUpdate = function (obj, $event) {
console.log(obj)
console.log($event)
console.log($event.target)
}
obj seems to return a scope value, however from what i've read I need to access $event.target, however $event is not defined. What am i doing wrong?
ng-change not allow to pass $event as parameter.
ng-change="otherBoxUpdate(test)"
var myapp = angular.module('app', []);
myapp.controller('Ctrl', function ($scope) {
$scope.otherBoxUpdate = function (obj) {
console.log(obj);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl as vm">
<input type="text" class="other-box" ng-model="test" id="4" ng-change="otherBoxUpdate(4)"/>
</div>
If you only need to identify the input that was clicked, you can pass some other piece of identifying information to your handler. For example, we can pass the id:
<input type="text" class="other-box" ng-model="test" id="4" ng-change="otherBoxUpdate(4)"/>

Revert ng-model value in Angular JS

Is it possible to revert the model value when displaying it?
My controller has this property:
this.config = {client: false, name: true};
And I want to use the values like this:
<label>
<input ng-model="ctrl.config.client"> Client
</label>
<div ng-hide="ctrl.config.client">Client</div>
I'd like to show the input checked when the config.client value is false. How can I do it?
UPDATE: If you want to check a checkbox, and you use $scope you can use ng-true-value="false" and ng-false-value="true" to revert the default values. This works only, if you use $scope instead of this! Here is an example:
<body ng-app="app">
<div ng-controller="ctrl">
<label>
<input type="checkbox" ng-model="config.client" ng-true-value="false" ng-false-value="true">
</label>
<div ng-hide="config.client">Client</div>
</div>
<script>
angular.module('app', []).controller('ctrl', function($scope) {
$scope.config = {client: false, name: true};
});
</script>
</body>
And the plunker to try it: http://plnkr.co/edit/vRIZMb2CpDQAKHu91yhN?p=preview
If I understand correctly I think you want ng-checked.
And then negate it. So something like:
<label>
<input type="checkbox" ng-checked="!ctrl.config.client" ng-model="ctrl.config.client"> Client
</label>
I am assuming you want a checkbox although it isn't clear from your example.

Angular - Binding checkboxes to ng-model from ng-repeat

I have some data coming back from a resource that looks like:
$scope.phones = [
{
Value: <some value>,
IsDefault: true
},
{
Value: <some value>
IsDefault: false
}
];
And for simplicity sake, here's the repeater:
<div ng-repeat="phone in phones">
<input type="radio" name="phone" ng-model="phone.IsDefault" />
</div>
I would like whichever radio is checked to update the model accordingly - this is not happening. On page load, nothing is checked. I can use ng-checked - but without ng-model it wont bind back to the array. Am I missing something simple or am I stuck writing an ng-change event to manually update the array?
As of now, I wrote a ng-change event as well, it currently looks like:
ng-model="phone.IsDefault" ng-value="true" ng-change="newPhoneSelected($index)"
$scope.newPhoneSelected = function (index) {
for (var i = 0; i < $scope.phones.length; i++) {
if (i == index) $scope.phones[i].IsDefault = true;
else $scope.phones[i].IsDefault = false;
}
}
You are missingng-value... it is radio button they work based on value to mark a value as selected. You need either [value="" | ng-value=""]
<input type="radio"
ng-model=""
[value="" |
ng-value=""]>
Like:
<input type="radio" ng-value="true" name="boolean" ng-model="myValue" /> True
<input type="radio" ng-value="false" name="boolean" ng-model="myValue" /> False
Here is a plunker demo
Or with strings values:
$scope.myValue = 'Car'
html
<input type="radio" ng-value="'Car'" name="string1" ng-model="myValue" /> Car
<input type="radio" ng-value="'Airplane'" name="string1" ng-model="myValue" /> Airplane
Here is the second demo
This is probably the closest sample to what you have:
http://jsfiddle.net/JbMuD/
A radio button is used to select one out of many values. You want to change the property of one item (isDefault = true) and simultaneously of another one (isDefault = false).
The semantically correct way would be to have some kind of defaultPhone value:
<div ng-repeat="phone in phones">
<input type="radio" name="phone" ng-model="temp.defaultPhone" ng-value="phone"/>
</div>
Since your model requires that each phone "knows" itself wether it's default or not, you can add a listener:
$scope.$watch('temp.defaultPhone', function(defaultPhone) {
$scope.phones.forEach(function(phone) {
phone.isDefault = phone === defaultPhone;
});
});
Here's a working example.

Categories

Resources