How to bind an array to checkbox using Angular2 ReactiveFormsModule? - javascript

I am new to Angular2 (started yesterday) and not an Angular user before this. My question is how can I 2 way bind an array to checkbox in ReactiveFormsModule?
Below is my missing piece puzzle code.
<!-- profile.ts -->
export class UserProfileComponent {
status = {
ready: false,
saving: false
};
form: FormGroup;
masterData = {
skills: [{ id: 'js', text: 'Javascript' }, { id: 'cs', text: 'C#' }]
};
constructor(FB: FormBuilder) {
let self = this;
self.form = FB.group({
name: new FormControl('', Validators.required)
, gender: new FormControl('', Validators.required)
, skills: new FormArray([])
})
self.getProfile()
.then(profile => {
return self.loadFormData(profile);
}).then(() => {
this.status.ready = true
});
}
getProfile() {
return new Promise((done, fail) => {
let sample = { name: 'me', gender: 'm', skills: ['js']};
done(sample);
})
}
loadFormData({ name, gender, skills = []}) {
let self = this
, form = self.form
return new Promise((done, fail) => {
form.get('name').setValue(name);
form.get('gender').setValue(gender);
skills.reduce((array: FormArray, skill: string) => {
array.push(new FormControl(skill));
return array;
}, form.get('skills'));
done();
});
}
selectSkill (event, skill) {
let skills = this.form.get('skills')
, checked = event.target.checked
;
let index = skills.value.indexOf(skill);
if (checked === true && index < 0) {
skills.push(new FormControl(skill));
} else if (checked === false && index >= 0) {
skills.removeAt(index);
}
}
};
<!-- profile.html -->
<div class="title">Profile</div>
<div>
<form [formGroup]="form" (ngSubmit)="submitForm()">
<div class="form-group">
<label for="name">Name</label>
<input formControlName="name" name="name" class="form-control" placeholder="Name" type="text">
</div>
<div class="form-group">
<label>Gender</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="m" formControlName="gender"> Male</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="f" formControlName="gender"> Female</label>
</div>
<div class="form-group">
<label>Skill {{ skills }}</label>
</div>
<div *ngFor="let skill of masterData.skills">
<div class="checkbox-inline"><label>
<input type="checkbox" name="skill" (change)="selectSkill($event, skill.id)"> {{ skill.text }}
</label></div>
</div>
<div>
<button type="submit" class="btn" [disabled]="form.invalid">Save</button>
</div>
</form >
</div>
Everything work fine except I don't know how to make skills checkbox checked after form load based on my sample data?

You have to use FormArrayName directive :
// Compoenent
public allSkills = [
{ value : 'cs', label : 'C#' },
{ value : 'js', label : 'Javascript' }
];
constructor(FB: FormBuilder) {
this.form = FB.group({
name: new FormControl('', Validators.required),
gender: new FormControl('', Validators.required),
skills: new FormArray([])
});
for(let skill on this.allSkills) {
this.form.get('skills').push(new FormControl());
}
}
// HTML
<form [formGroup]="form" (ngSubmit)="submitForm()">
<div class="form-group">
<label for="name">Name</label>
<input formControlName="name" name="name" class="form-control" placeholder="Name" type="text">
</div>
<div class="form-group">
<label>Gender</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="m" formControlName="gender"> Male</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="f" formControlName="gender"> Female</label>
</div>
<div class="form-group">
<label>Skills</label>
</div>
<div formArrayName="skills">
<div class="checkbox-inline" *ngFor="let skill of skills.controls; let i=index">
<label>
<input type="checkbox" [formControlName]="i" [value]="allSkills[i]['value']"/> {{allSkills[i]['label']}}
</label>
</div>
</div>
<button type="submit" class="btn" [disabled]="form.invalid"> Save </button>
</form>

Related

Dynamic generated form with checkbox in Vue

I have dynamic generated form in Vue. Every loop have v-model. Everything work fine. But when I use checkboxes v-model work for all loops not on one like in input type text. Can You help me solved this problem? Below Vue code:
<fieldset>
<div class="form-row mb-2" v-for="input, index in journal" :key="index">
<div class="col-auto">
<label for="date">Data</label>
<Datepicker v-model="input.date" input-class="form-control" :input-attr="{id: 'date', name: 'date'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="timeStart">Od</label>
<Datepicker type="time" v-model="input.timeStart" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeStart', name: 'timeStart'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="timeEnd">Do</label>
<Datepicker type="time" v-model="input.timeEnd" format="HH:mm" input-class="form-control" :input-attr="{id: 'timeEnd', name: 'timeEnd'}" style="width: 100%;" />
</div>
<div class="col-md-2">
<label for="players">Lista obecności</label>
<div class="form-check" v-for="item in input.players">
<input v-model="item.checked" type="checkbox" class="form-check-input" :id="'id-'+item.id+'set'+index">
<label class="form-check-label" :for="'id-'+item.id+'set'+index">{{ item.fullName }}</label>
</div>
</div>
<div class="col-auto">
<label for="description">Opis</label>
<textarea v-model="input.description" class="form-control" rows="7" id="description" placeholder="Opis"></textarea>
</div>
<div class="col-auto" #click="addInput" v-show="index == journal.length-1 && journal.length < 16">
<ButtonVue style="margin-top: 30px;" title="Dodaj" type="button" cancelWidth="true" color="btn-success"><i class="fas fa-plus"></i></ButtonVue>
</div>
<div class="col-auto align-self-start" #click="removeInput(index)" v-show="index || ( !index && journal.length > 1)">
<ButtonVue style="margin-top: 30px;" title="Usuń" type="button" cancelWidth="true" color="btn-danger"><i class="fas fa-minus"></i></ButtonVue>
</div>
</div>
</fieldset>
 
data() {
return {
contact: [],
journal: [{
date: "",
timeStart: "",
timeEnd: "",
players: "",
description: ""
}],
contacts: [],
}
},
Methods:
Method for creating dynamic form
addInput() {
this.journal.push({
date: "",
timeStart: "",
timeEnd: "",
players: this.contact,
description: ""
});
},
And here is the method which gets players from contacts
getContacts() {
this.pageLoader = true;
this.$http.get('/pkpar/get-contacts')
.then(({
data
}) => {
this.contacts = data.contacts;
for(let i=0; i<this.contacts.length; i++)
{
this.contact.push({'id': this.contacts[i]['id'], 'fullName' :
this.contacts[i]['fullName'], 'checked': true});
}
this.journal[0].players = this.contact;
this.pageLoader = false;
})
.catch(error => {
console.log(error);
});
},
Your addInput method creates and pushes new object into journal array, but each object created this way has a players property which references same array (this.contact)
The Difference Between Values and References in JavaScript
Easiest (but not most optimal) way to handle this is to create a copy of the array and objects inside for each new journal:
addInput() {
this.journal.push({
date: "",
timeStart: "",
timeEnd: "",
players: this.contact.map((player) => ({ ...player })),
description: ""
});
},

Show a preview/Edit option before submitting the form using AngularJS

I have my html form as shown below:
<div class="container">
<div class="form-group" ng-controller="studentController">
<form role="form" class="well form-horizontal" id="registerForm" name="forms.registerForm">
<div class="form-group">
<label class="col-md-4 control-label">First Name </label>
<input ng-model="formdata.firstname" required type="text" name="firstname">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Middle Name </label>
<input ng-model="formdata.middlename" required type="text" name="middlename" maxlength="1">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Last Name </label>
<input ng-model="formdata.lastname" required type="text" name="lastname">
</div>
<div class="form-group">
<label for="email" class="col-md-4 control-label">E-mail address</label>
<input ng-model="formdata.email" required type="email">
</div>
<div class="form-group">
<label class="col-md-4 control-label">Student ID</label>
<input ng-model="formdata.studentid" required type="number">
</div>
<div required class="form-group">
<label class="col-md-6 control-label">
level
</label> <br>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="300" checked>
300 </label>
</div>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="400">
400 </label>
</div>
<div class="radio">
<label class="col-md-6 control-label">
<input type="radio" ng-model="formdata.type" value="500">
500 </label>
</div>
</div>
<div class="form-group" align="center">
<input type="file" ngf-select ng-model="formdataa.file" name="file" ngf-pattern="'application/pdf'" accept="'.pdf'" ngf-max-size="5MB" required ngf-model-invalid="errorFile">
</div>
<div class="container" align="center">
<button class="btn btn-register" ng-click="tempData()" ng-disabled="forms.registerForm.$invalid" >Submit</button>
</div>
Below is the angular javascript code to store the details of the form and the file in the server.
$scope.tempData = function(ev){
console.log($scope.formdata);
var confirm = $mdDialog.confirm()
.title('Are you sure you want to delete this user?')
.ok('YES')
.cancel('CANCEL');
$mdDialog.show({
locals:{formdata: $scope.formdata, dataToPassFile: $scope.formdataa}, //here where we pass our data
controller: _DialogController,
controllerAs: 'vd',
templateUrl: 'scripts/app/studentdialog/studentdialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true
})
.then(
function(answer) {},
function() {
}
);
};
function _DialogController($scope, $mdDialog, formdata,dataToPassFile) {
$scope.closeDialog = function() {
$mdDialog.hide();
};
$scope.firstname = formdata.firstname;
$scope.lastname = formdata.lastname;
$scope.middlename = formdata.middlename;
$scope.studentid = formdata.studentid;
$scope.email = formdata.email;
$scope.type = formdata.type;
$scope.file = dataToPassFile.file;
console.log('FIle Passed' +dataToPassFile.file);
$scope.tfile = function () {
console.log("TFIle Called");
if ($scope.forms.registerForm.file.$valid && $scope.formdataa.file) {
$scope.upload($scope.formdataa.file);
}
};
$scope.upload = function (file) {
file.upload = Upload.upload({
url: $rootScope.baseURL + 'php/uploadT.php',
method: 'POST',
data: {
'file': file,
'userId': $scope.formdata.firstname,
'type': $scope.formdata.type
},
});
$scope.register = function () {
console.log("clicked");
$scope.loading = true;
AppServices.register($scope.formdata)
.then(function (result) {
if (Object.keys(result).length > 0) {
// update current users list
if (result.type == '300' || result.type == '400') {
$scope.users.300.push(result);
} else {
console.log(result);
$scope.users[result.type] = result;
}
$scope.forms.registerForm.$setPristine();
$scope.forms.registerForm.$setUntouched();
$scope.msg = {};
$scope.msg.successRegister = 'Registered Successfully';
} else {
$scope.msg = {};
$scope.msg.errorRegister = 'Email already exists!';
}
})
.finally(function (data) {
$scope.loading = false;
});
};
When the user clicks on Submit button, I want to create a confirmation page where it will give the user all the details again so the user can confirm and then actually submit the form. Kindly let me know how can I use localStorage for storing and retrieving the data at the same time for confirm page.
Thank you in advance!
UPDATE: I created a MDDialog and calling it when the button is clicked,I can see all the data as well in MDDialog now. When user clicks on OK, I want the data on the page(not the data on the MDDialog) to be submited in the backend(php), how can I do that?
Why not show this info on a modal, and call the confirmation function in the same controller where you are, after the modal is closed. This way you won't need any caching policy.

In react, how do select/checked the radio buttons?

I am not able to click or select on any of my radio buttons. Can someone help me out how to work with radio buttons in react?
I tried removing e.preventDefault() but that didn't help either.
Here's what my code looks like:
File 1:
this.state = {
fields: {
gender: ''
}
}
fieldChange(field, value) {
this.setState(update(this.state, { fields: { [field]: { $set: value } } }));
}
<Form
fields={this.state.fields}
onChange={this.fieldChange.bind(this)}
onValid={() => handleSubmit(this.state.fields)}
onInvalid={() => console.log('Error!')}
/>
File 2:
render() {
const { fields, onChange, onValid, onInvalid, $field, $validation } = this.props;
return (
{/* Gender */}
<div id={styles.genderField} className={`form-group ${styles.formGroup} ${styles.projName}`}>
<label className="col-sm-2 control-label">Gender:</label>
<div className="col-sm-10">
<label className="radio-inline">
<input type="radio" name="gender" id="male"
checked={fields.gender === "Male"}
value={fields.gender} {...$field( "gender", e => onChange("gender", e.target.value)) } />
Male
</label>
<label className="radio-inline">
<input type="radio" name="gender" id="female"
checked={fields.gender === "Female"}
value={fields.gender} {...$field( "gender", e => onChange("gender", e.target.value)) } />
Female
</label>
</div>
</div>
<div className={`modal-footer ${styles.modalFooter}`}>
<button
className={`btn btn-primary text-white ${styles.saveBtn}`}
onClick={e => {
e.preventDefault();
this.props.$submit(onValid, onInvalid);
}}
>
Save
</button>
</div>
)
}
That's not how the docs handle onChange events. https://reactjs.org/docs/handling-events.html
You need to provide the full code to be able to help with that particular component.
Check out this working example: https://stackblitz.com/edit/react-radiobtns
class App extends Component {
constructor(props) {
super(props);
this.state = {selectedOption: 'option1'};
// This binding is necessary to make `this` work in the callback
this.handleOptionChange = this.handleOptionChange.bind(this);
}
handleOptionChange(changeEvent) {
this.setState({
selectedOption: changeEvent.target.value
});
}
render() {
return (
<form>
<label>
<input
onChange={this.handleOptionChange}
type="radio" value="option1"
checked={this.state.selectedOption === 'option1'}
name="radio1"/>
Option 1
</label>
<label>
<input
onChange={this.handleOptionChange}
checked={this.state.selectedOption === 'option2'}
type="radio"
value="option2"
name="radio1"/>
Option 2
</label>
<label>
<input
onChange={this.handleOptionChange}
checked={this.state.selectedOption === 'option3'}
type="radio"
value="option3"
name="radio1"/>
Option 3
</label>
</form>
);
}
}

Angular 4 Nested FormArrays Cannot read property 'push' of null

I cannot push to an array.
i have a segment(id, time) that can have one or several people (role, infos). the field are generated dynamically. On load the page shows the fields (see image below).
when try to add a person I get error : ERROR TypeError: Cannot read property 'push' of null
Here is the .ts code:
addPerson(index: number) {
//let personRows3 = <FormArray>this.mySummaryForm.get('personRows3');
let personRows3 = <FormArray>this.mySummaryForm.get(`segmentRows3.${index}.personRows3`)
personRows3.push(this.fb.group({
personR3: '',
personI3: ''
}));
}
segmentRows3: this.fb.array([
this.fb.group({
segmentId3: '',
segmentTime3: '',
personRows3: this.fb.array([
this.fb.group({
personR3: '',
personI3: ''
})
])
})
]),
The .html code
<div formArrayName="segmentRows3">
<div *ngFor=" let segmentRow of mySummaryForm.controls.segmentRows3.controls; let i=index " >
<div class="form-group" [formGroupName]="i" > {{i+1}}
<label for="segmentId3">Segment ID
<select formControlName="segmentId3" formControlName="segmentId3" placeholder="pick" type="text" id="segmentId3" class="form-control" [(ngModel)]="levelNumSegment3" (ngModelChange)="toNumberSegment3()">
<option *ngFor="let level of segmentId" [value]="level.num">{{level.name}}</option>
</select>
</label>
<label for="segmentTime3">Segment time
<input formControlName="segmentTime3" type="text" id="segmentTime3" class="form-control" placeholder="select a time" (ngModelChange)="onChange($event)">
</label>
<div formArrayName="personRows3">
<div *ngFor=" let personRow of segmentRow.controls.personRows3.controls; let j=index " >
<div class="form-group" [formGroupName]="j" > {{j+1}}
<label for="personR3">person Role
<input formControlName="personR3" [typeahead]="personRole" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personR3" class="form-control" placeholder="select a role" (ngModelChange)="onChange($event)" >
</label>
<label for="personI">Person infos
<input formControlName="personI3" [typeahead]="states" [typeaheadOptionsLimit]="10" [typeaheadMinLength]="0" type="text" id="personI3" class="form-control" placeholder="select infos" (ngModelChange)="onChange($event)" >
</label>
<label><span (click)="deletePerson(j)" class="btn btn-danger">Remove</span></label>
</div>
</div>
</div>
<br><button type="button" (click)="addPerson(j)" class="btn btn-info">Add a person</button><br><br><br>
</div>
</div>
</div>
The above error will occur when your personRows3 is null or don't have elements.
Add a check before pushing the elements,
if(personRows3){
personRows3.push(this.fb.group({
personR3: '',
personI3: ''
}));
}

How can i check radio button by default?

On page load i want to show below radio button selected by default i used html attribute but its not working. So on page load I want to show all process radio button checked by default. Is there any other way to achieve this task?
radio.html
<div class="panel panel-default">
<div class="panel-heading">View/Search Inventory</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterOptions"
k-ng-model="kfilter" ng-model="filter" ng-change="onChange()"></select>
</div>
<div ng-show="filter=='PROCESS'" ng-init="search.showCriteria='allProcess';onChange()">
<div class="col-md-7">
<label class="radio-inline" for="allProcess"> <input
type="radio" name="optionsRadios1" ng-value="'allProcess'"
id="allProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show All Processes
</label> <label class="radio-inline" for="ratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'ratedProcess'"
id="ratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Rated Processes
</label> <label class="radio-inline" for="unratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'unratedProcess'"
id="unratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unrated Processes
</label>
</div>
</div>
<div ng-show="filter=='RISK'">
<div class="col-md-7">
<label class="radio-inline" for="allRisk"> <input
type="radio" name="optionsRadios1" ng-value="'allRisk'"
id="allRisk" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Risks
</label> <label class="radio-inline"> <input type="radio"
name="optionsRadios1" ng-value="'unalignedRisk'"
ng-model="search.showCriteria" ng-change="selectSearchType()">
Show Unaligned Risks
</label>
</div>
</div>
<div ng-show="filter=='CONTROL'">
<div class="col-md-7">
<label class="radio-inline" for="allControl"> <input
type="radio" name="optionsRadios1" ng-value="'allControl'"
id="allControl" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Controls
</label> <label class="radio-inline" for="unalignedControl"> <input
type="radio" name="optionsRadios1" ng-value="'unalignedControl'"
id="unalignedControl" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unaligned Controls
</label>
</div>
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" ng-click="search(0)">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
<div class="row">
<!--<label for="filterBy" class="col-md-1">Filter by: </label>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'" k-option-label="'Select'"
k-data-value-field="'value'" k-data-source="filterByOptions"
k-ng-model="kfilterBy" ng-model="filterBy" style="width: 100%"></select>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterByValues" k-option-label="'Select'"
k-ng-model="kfilterByValue" ng-model="filterByValue" style="width: 100%"></select>
</div> -->
<div class="col-md-3">
<a href="" ng-show="!showAdvance" ng-click="advanceFilter()">Advanced
Search</a> <a href="" ng-show="showAdvance" ng-click="advanceFilter()">Basic
Search</a>
<!-- <button ng-show="!showAdvance" class="btn btn-default" type="button" ng-click="search()">Go</button> -->
</div>
</div>
<form role="form" name="formTimeLine" kendo-validator="validator"
k-options="myValidatorOptions">
<div ng-show="showAdvance">
<div class="clone" ng-repeat="input in inputs">
<br />
<div class="row">
<div class="col-md-1">
<a ng-if="inputs.length < searchOptions.length"
class="add col-md-1" name="addnumadd" ng-click="add($index)"> </a>
<a ng-if="inputs.length >1" class="delete col-md-1"
name="deletenumadd" ng-click="remove($index)"> </a>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-option-label="'Select'" k-data-value-field="'value'"
k-data-source="searchOptions" name="searchBy-{{$index}}"
ng-model="input.searchBy"
data-required-msg="Please select the value"
ng-change="clearPreviousValue({{$index}})" data-duplicate=""
style="width: 100%" required></select>
</div>
<div class="col-md-3">
<input type="text" class="form-control"
ng-model="input.searchValue" placeholder="Enter search item"
ng-maxlength="256" name={{$index}}>
</div>
<div class="col-md-4">
<input type="radio" name={{$index}} value="exactMatch"
ng-model="input.exactMatch" data-requiredCheckbox=""> Exact
Match <input type="radio" name={{$index}} value="contains"
ng-model="input.exactMatch" data-requiredCheckbox=""> Contains
<span class="k-invalid-msg" data-for={{$index}}></span>
</div>
</div>
</div>
</div>
</form>
</div>
<div id="outergrid" class="row">
<ng-include src="gridInclude"></ng-include>
</div>
</div>
radio.js
$scope.processSearchOptions = processSearchOptions;
$scope.riskSearchOptions = riskSearchOptions;
$scope.controlSearchOptions = controlSearchOptions;
$scope.filterByOptions = filterByOptions;
$scope.filterByValues = filterByValues;
$scope.searchOptions = processSearchOptions;
$scope.onChange = function () {
var value = $scope.filter;
$scope.postArgs.page = 1;
if (value === 'PROCESS') {
$scope.search.showCriteria = 'allProcess';
$scope.searchOptions = processSearchOptions;
$scope.gridInclude = 'views/viewAll/processGrid.html';
}
if (value === 'RISK') {
$scope.search.showCriteria = 'allRisk';
$scope.searchOptions = riskSearchOptions;
$scope.gridInclude = 'views/viewAll/riskGrid.html';
}
if (value === 'CONTROL') {
$scope.search.showCriteria = 'allControl';
$scope.searchOptions = controlSearchOptions;
$scope.gridInclude = 'views/viewAll/controlGrid.html';
}
$scope.showAdvance = false;
$scope.clearAdvFilter();
$scope.postArgs = {
page: 1
};
};
//initialize process grid
initializeGrid('process');
$scope.processGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.processGridColumns);
$scope.processInnerGridOptions = viewSearchInvService.getInnerProcessGrid;
//initialize risk grid
initializeGrid('risk');
$scope.riskGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.riskGridColumns);
$scope.riskInnerGridOptions = viewSearchInvService.getInnerRiskGrid;
//initialize control grid
initializeGrid('control');
$scope.controlGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.controlGridColumns);
$scope.controlInnerGridOptions = viewSearchInvService.getInnerControlGrid;
$scope.ProcessEditHandler = function (id) {
ViewEditPrcsService.saveProcessId(id);
};
$scope.RiskEditHandler = function (id) {
ViewEditRiskService.saveRiskId(id);
};
$scope.advanceFilter = function () {
if ($scope.showAdvance) {
$scope.clearAdvFilter();
$scope.showAdvance = false;
} else {
$scope.showAdvance = true;
}
};
$scope.clearAdvFilter = function () {
$scope.inputs = [];
$scope.inputs.push(getNewObject());
};
$scope.search = function () {
if ($scope.validator.validate() || !$scope.showAdvance) {
searchCriteria(1);
searchFlag = true;
if ($scope.filter === 'PROCESS') {
$scope.search.process.dataSource.read();
}
if ($scope.filter === 'RISK') {
$scope.search.risk.dataSource.read();
}
if ($scope.filter === 'CONTROL') {
$scope.search.control.dataSource.read();
}
}
};
$scope.selectSearchType = function () {
$scope.clearAdvFilter();
$scope.showAdvance = false;
$scope.search();
};
$scope.add = function () {
$scope.inputs.push(getNewObject());
};
$scope.remove = function (index) {
$scope.inputs.splice(index, 1);
};
$scope.myValidatorOptions = {
rules: {
duplicate: function (input) {
return checkDuplicates(input.val(), input[0].name);
},
requiredCheckbox: function (input) {
return !(input[0].type === 'radio' && !$scope.inputs[input[0].name].exactMatch && !$scope.inputs[input[0].name].contains);
}
},
messages: {
duplicate: 'Option already selected. please select another option',
requiredCheckbox: 'Operator is required'
}
};
$scope.clearPreviousValue = function (index) {
$scope.inputs[index].searchValue = '';
};
});
Without knowing more about the specifics of when you want this checked, apply the following using ngChecked. In this case, checked if true, but this can be any expression
ng-checked="true"
JSFiddle Link
In response to your updated code, you could leverage ngInit on your parent <div> for defaulting one radio button in a group. Note for isolating the direct issue I have slimmed down most of this markup
<div ng-init="search.showCriteria='allProcess'">
Updated JSFiddle Link
You need to make sure your model is set to the value of the radio box.
$scope.search.showCriteria = 'allProcess'
As a side node, you don't need to be using ng-value here. You could use just use value="allProcess" because ng-value is only needed for Angular expressions, not plain strings.

Categories