Not able to set checkbox default checked while using angularjs - angularjs

I want to set default value of checkbox to checked ie., user must see that check box is checked when opening the page for some reason it does not work while using angularjs
here is my code
<html ng-app>
<input type="radio" name="lookup" ng-model="lookup" value="1" ng-checked="lookup==1" checked>Employee Lookup</input>
<input type="radio" name="lookup" ng-model="lookup" value="2" ng-checked="lookup==2">Company Lookup</input>
</html>

Since you're using ngModel and value, the radio will automatically be selected if they match. Here is the HTML and JS:
<html ng-app ng-controller="testcontroller">
<input type="radio" ng-model="lookup" value="1">Employee Lookup</input>
<input type="radio" ng-model="lookup" value="2">Company Lookup</input>
</html>
function testcontroller($scope){
$scope.lookup = 1;
}
And here is a working jsFiddle demonstration: http://jsfiddle.net/BinaryMuse/ZQDts/3/ (You might have been having trouble with your jsFiddle because you misspelled ng-app.)

Related

What is difference in ways of setting radio button checked=true in AngularJS

If I set radio button default selection using ng-checked="$first" then it got checked. If I use ng-checked="true" radio button doesn't get checked?
Kindly explain when this can happen?
I cant use $first acc to my Use case
One thing to note about radio buttons once you check they cant be unchecked. You must have to provide another options. I prepared some samples for you.
In 1st method eventhough i set the value to true in controller and set the value to 1 it got checked.this is the most optimal solution.
2nd method using ng-checked eventhough i change the value but ng-model values are not updated. so you have to use ng-change function and track every ng-model.personally nobody like this method.
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.myradio = true;
$scope.myradio_ng1 = true;
$scope.myradio_ng2 = false;
$scope.first = true; // probably you are getting this from db
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Radio</title>
</head>
<body ng-controller="MainCtrl">
<p>1. Using ng-model</p>
<div>
<label for="myradio1">Yes</label>
<input type="radio" ng-model="myradio" name="myradio" id="myradio1" value="1" />
<label for="myradio2">No</label>
<input type="radio" ng-model="myradio" name="myradio" id="myradio2" value="0"/>
</div>
<div>Radio value: {{myradio}}</div>
<p>2. Using ng-checked</p>
<div>
<label for="myradio3">First</label>
<input type="radio" name="myradiong" id="myradio3" ng-checked="myradio_ng1" />
<label for="myradio4">Second</label>
<input type="radio" name="myradiong" id="myradio4" ng-checked="myradio_ng2"/>
<div>Radio value for first: {{myradio_ng1}}</div>
<div>Radio value for Second: {{myradio_ng2}}</div>
</div>
<p>Your case</p>
<label for="first">First</label>
<input type="radio" id="first" ng-checked="first" />
</body>
</html>
In your case you have an element you want to checked when it is true. In your controller set the value of $scope.first to true or false then in your view use ng-checked="first". Find the result by running the code snippet.

ng-disabled and form validation

When using angular's (1.5) forms support, I would expect that when a field is disabled, it should not be marked as invalid, because the user cannot possibly change the value.
However, as seen in the plunker below, where a field is required, but can be switched from enabled to disabled and visa versa by the checkbox, the form validation result does not change, the whole form is still invalid, although the value cannot be changed if the field is disabled.
http://plnkr.co/edit/OMZkoPgPZcHjO67JF88c?p=preview
Together with showing validation messages and submitting the form this poses a problem in UX and flexibility to use the angular validations to determine the state of the form and if it is ok to "submit it" (send AJAX to the server).
(the code below is in the plunker, I just pasted it here, because the code is required when linking plunker)
<form name="vm.form" novalidate>
<input ng-model="vm.model" ng-disabled="vm.disabled" required />
<label><input type="checkbox" ng-model="vm.disabled" />Disable field</label>
</form>
Form is invalid: {{vm.form.$invalid}}
Ok preety much here you dont normally do ng-disabled on the fields just on like the submit button as shown:
<input ng-model="vm.model" ng-minlength="4" ng-required="true"/>
<label><input type="checkbox" ng-model="vm.disabled" ng-required="true"/>Disable field</label>
<br><input type="submit" ng-disabled="vm.form.$invalid"/>
</form>
Form is invalid: {{vm.form.$invalid}}
</body>
</html>
Now if you try this it will work correctly as shown in Plunker.
you can manipulate the value of ng-required value based on whether the checkbox value is checked or not
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angularjs#1.5.0" data-semver="1.5.0" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="Asd as vm">
<form name="vm.form" novalidate>
<input ng-model="vm.model" ng-disabled="vm.checkbox" ng-required="vm.checkbox===false" />
<label><input type="checkbox" ng-model="vm.checkbox" />Disable field</label>
<input ng-model="vm.other" required/>
</form>
Form is invalid: {{vm.form.$invalid}}
</body>
</html>

How to populate a text box using ng-bind?

I'm new to AngularJS and I am going through this link and I am curious to do the experiment on a text box control using ng-bind. But it is not working.
<html>
<title>AngularJS First Application</title>
<body>
<h1>Sample Application</h1>
<div ng-app="">
<p>Enter your Name: <input type="text" ng-model="name"></p>
<input type ="text" ng-bind="name" />
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</body>
</html>
How can I populate a text box using ng-bind?
As, The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes, you will not be able to bind to an input box:
<input type ="text" ng-bind="name" />
You can instead use ng-value
<input type="text" ng-value="name" />
or you can populate your input box using the model within the value attribute.
<input type="text" value="{{name}}" />
See this codepen

Radio Buttons ng-checked with ng-model

In my HTML page, I have two sets of Boolean based radio buttons: Labeled: "Yes" and "No" / Values: True and False respectively. I'm populating a full form from a PostgreSQL database table to allow the authenticated user to view the form with populated data and edit the populated fields including the radio buttons, then save the form which will save the data to the DB. All of the other text fields populate without issue; it's both collection of radio buttons I am having an issue with pre-checkmarking the radio buttons.
The below does not pre-populate the checked on front end (but adds the correct attribute of checked in HTML source):
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" value="FALSE" ng-checked="person.billing == 'false'" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" value="TRUE" ng-checked="person.billing == 'true'" />
However, this does check the correct radio button on load:
<input id="billing-no" type="radio" name="billing" value="FALSE" ng-checked="person.billing == 'false'" />
<input id="billing-yes" type="radio" name="billing" value="TRUE" ng-checked="person.billing == 'true'" />
Note: I needed to check against the string boolean value in the directive ng-checked since the boolean value always comes back as a string from PostgreSQL. This, apparently, was a part of PostgreSQL's design when querying data from columns that have boolean data types.
When adding the ng-model directive, the radio button no longer is checked (at least in the rendered browser view). The odd part is that I looked at the source and it clearly checks the correct one. What's even more odd, is that I have to click on the radio button twice to 'check' it. I've tested this in latest version of Chrome, FF, and IE and it all results in the same issue.
The question is: when adding the ng-model directive, why would the HTML source add 'checked' in the radio button attribute, but seemingly does not mark the radio button? Furthermore, why would I have to click twice on the radio button that IS supposed to be checked?
Solution:
To fix this, I removed the ng-checked directive from the radio buttons and only used ng-model as suggested by #Cypher and #aet. I then replaced the attribute value with the directive ng-value "true" & "false". After, I set the values in the controller.
HTML
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="false" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="true" />
Angular JS
app.controller('peopleCtrl', function($scope, peopleFactory){
...
peopleFactory.getPerson(personParams).then(function(data){
$scope.person = data;
/* moved from ng-checked */
$scope.person.billing = data.billing == 'true';
});
...
};
I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
The code from the example should not be difficult to adapt to your specific situation:
<script>
function Ctrl($scope) {
$scope.color = 'blue';
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
I solved my problem simply using ng-init for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
[Personal Option]
Avoiding using $scope, based on John Papa Angular Style Guide
so my idea is take advantage of the current model:
(function(){
'use strict';
var app = angular.module('way', [])
app.controller('Decision', Decision);
Decision.$inject = [];
function Decision(){
var vm = this;
vm.checkItOut = _register;
function _register(newOption){
console.log('should I stay or should I go');
console.log(newOption);
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div ng-app="way">
<div ng-controller="Decision as vm">
<form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">
<label class="radio-inline">
<input type="radio" name="option" ng-model="decision.myWay"
ng-value="false" ng-checked="!decision.myWay"> Should I stay?
</label>
<label class="radio-inline">
<input type="radio" name="option" ng-value="true"
ng-model="decision.myWay" > Should I go?
</label>
</form>
</div>
</div>
I hope I could help ;)
Please explain why same ng-model is used? And what value is passed through ng- model and how it is passed? To be more specific, if I use console.log(color) what would be the output?

AngularJS: ng-model not binding to ng-checked for checkboxes

I referred to this before asking this question: AngularJs doesn't bind ng-checked with ng-model
If ng-checked is evaluated to true on the html side, the ng-model is not updated. I can't ng-repeat as suggested in the above question because I have to use some styling for each checkbox.
Here is the plunker that I have created to illustrate my problem.
http://plnkr.co/edit/YsOsPh3vjkPMUUDa6r2t
To see what I want, please open the console, and just click on Submit button. Please don't check any checkboxes.
ngModel and ngChecked are not meant to be used together.
ngChecked is expecting an expression, so by saying ng-checked="true", you're basically saying that the checkbox will always be checked by default.
You should be able to just use ngModel, tied to a boolean property on your model. If you want something else, then you either need to use ngTrueValue and ngFalseValue (which only support strings right now), or write your own directive.
What is it exactly that you're trying to do? If you just want the first checkbox to be checked by default, you should change your model -- item1: true,.
Edit: You don't have to submit your form to debug the current state of the model, btw, you can just dump {{testModel}} into your HTML (or <pre>{{testModel|json}}</pre>). Also your ngModel attributes can be simplified to ng-model="testModel.item1".
http://plnkr.co/edit/HtdOok8aieBjT5GFZOb3?p=preview
You can use ng-value-true to tell angular that your ng-model is a string.
I could only get ng-true-value working if I added the extra quotes like so (as shown in the official Angular docs - https://docs.angularjs.org/api/ng/input/input%5Bcheckbox%5D)
ng-true-value="'1'"
What you could do is use ng-repeat passing in the value of whatever you're iterating on to the ng-checked and from there utilising ng-class to apply your styles depending on the result.
I did something similar recently and it worked for me.
Can Declare As the in ng-init also getting true
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl" ng-init="testModel['item1']= true">
<label><input type="checkbox" name="test" ng-model="testModel['item1']" /> Testing</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3</label><br />
<input type="button" ng-click="submit()" value="Submit" />
</body>
</html>
And You Can Select the First One and Object Also Shown here true,false,flase
The ng-model and ng-checked directives should not be used together
From the Docs:
ngChecked
Sets the checked attribute on the element, if the expression inside ngChecked is truthy.
Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.
— AngularJS ng-checked Directive API Reference
Instead set the desired initial value from the controller:
<input type="checkbox" name="test" ng-model="testModel['item1']" ̶n̶g̶-̶c̶h̶e̶c̶k̶e̶d̶=̶"̶t̶r̶u̶e̶"̶ />
Testing<br />
<input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2<br />
<input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3<br />
<input type="button" ng-click="submit()" value="Submit" />
$scope.testModel = { item1: true };
You don't need ng-checked when you use ng-model. If you're performing CRUD on your HTML Form, just create a model for CREATE mode that is consistent with your EDIT mode during the data-binding:
CREATE Mode: Model with default values only
$scope.dataModel = {
isItemSelected: true,
isApproved: true,
somethingElse: "Your default value"
}
EDIT Mode: Model from database
$scope.dataModel = getFromDatabaseWithSameStructure()
Then whether EDIT or CREATE mode, you can consistently make use of your ng-model to sync with your database.
I had this issue while i am working with the angular js migration from 1.2 to 1.3.
The input type checkbox was not triggered if it was initiated from controller as well as the ng change event also not triggered. I tried with all types since ng model along with ng checked wont work.
Then ended with simple thing it worked for me like removing the ng change event by replacing with ng click.

Resources