Pass array just what user selects - arrays

I want to pass data what user checked. My problem now.. it pass all..
This is my demo code and stackblitz
HTML
<div class="row" *ngFor="let item of modules; let i = index;">
<div class="col-md-1 align-center">{{i+1}}</div>
<div class="col-md-5">
<input type="text" class="form-control" [(ngModel)]="modules[i].module_name" value="{{modules[i].module_name}}" disabled>
</div>
<div class="col-md-2">
<input type="radio" class="form-control" [checked]="modules[i].action.read" (change)="modules[i].action.read" name="access_{{modules[i].company_id}}" id="package-1">
<label for="package-1">Read</label>
</div>
<div class="col-md-2">
<input type="radio" [checked]="modules[i].action.write" (change)="modules[i].action.write" class="form-control" name="access_{{modules[i].company_id}}" id="package-2">
<label for="package-2">write</label>
</div>
<button (click)="test(item)">test</button>
</div>
Component
test(val){
console.log(val)
}

There are two issues mainly:
You need to create a unique id for both label and id attributes within the for-loop.
Next, create a method that will toggle the read/write property of each individual module. This ensures that if read is set then write will be false and vice versa.
.ts
toggleReadWrite(module: any, isRead: boolean) {
if (isRead) {
module.action.read = !module.action.read;
module.action.write = false;
} else {
module.action.write = !module.action.write;
module.action.read = false;
}
}
.html
<div class="row" *ngFor="let item of modules; let i = index;">
<div class="col-md-1 align-center">{{i+1}}</div>
<div class="col-md-5">
<input type="text" class="form-control" [(ngModel)]="modules[i].module_name"
value="{{modules[i].module_name}}" disabled>
</div>
<div class="col-md-2">
<input type="radio" class="form-control" [checked]="modules[i].action.read"
(change)="toggleReadWrite(modules[i], true)"
name="access_{{modules[i].company_id}}" id="package+1+{{i}}">
<label for="package+1+{{i}}">Read</label>
</div>
<div class="col-md-2">
<input type="radio" [checked]="modules[i].action.write"
(change)="toggleReadWrite(modules[i], false)" class="form-control"
name="access_{{modules[i].company_id}}" id="package+2+{{i}}">
<label for="package+2+{{i}}">write</label>
</div>
<button (click)="test(item)">test</button>
</div>

First of all, you should make the id of radio buttons unique as you are looping through it.
id="package-1{{i}}"
<input type="radio" class="form-control" [checked]="modules[i].action.read" (change)="modules[i].action.read" name="access_{{modules[i].company_id}}"
id="package-1{{i}}">
<label for="package-1{{i}}">Read</label>
Also, I am not sure what is your desired output, please explain more.

Related

ng-if and ng-model not working together for checkbox

there is a form which have two checkbox option one is English and another one is Hindi.On the basis of language selection div(child form) will open.but i have a condition if child form or div have some value then on page load checkbox will be check and div will be on open state.
Code which i try is-
<label class="radio-inline" ng-if="$ctrl.astrologerLanguageDetails.IsEnglishValue === true" >
English <input type="checkbox" ng-checked="true"><br /><br />
</label>
<label class="radio-inline" ng-if="!$ctrl.astrologerLanguageDetails.IsEnglishValue === true">
English <input type="checkbox" ng-model="ENchkselct" ><br /><br />
</label>
and this is my div
<div ng-if="$ctrl.astrologerLanguageDetails.IsEnglishValue === true && astroProfile.LanguageId ==='EN' ||ENchkselct" ng-show="ENchkselct">
<div class="col-sm-6 h3"><b>English Profile Translation</b></div><br /><br /><div class="clearfix"></div>
<div class="form-group">
<label class="col-sm-2 control-label">Display First Name</label>
<div class="col-sm-6">
<input type="text" name="profileengfirstname" ng-model="astroProfile.FirstName" class="form-control" />
<!--<span ng-show="astroProfileform.$submitted && astroProfileform.profileengfirstname.$error.required">
Profile First Name is required.
</span>-->
</div>
<label class="col-sm-1 control-label" ng-if="astroProfile.FirstName=== null"><span class="label label-danger">Incomplete</span></label>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Display Last Name</label>
<div class="col-sm-6">
<input type="text" name="profileenglastname" ng-model="astroProfile.LastName" class="form-control" />
<!--<span ng-show="astroProfileform.$submitted && astroProfileform.profileenglastname.$error.required">
Profile Last Name is required.
</span>-->
</div>
<label class="col-sm-1 control-label" ng-if="astroProfile.LastName === null"><span class="label label-danger">Incomplete</span></label>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Profile Description</label>
<div class="col-sm-6">
<textarea name="profileengresumetext" ng-model="astroProfile.ResumeText" class="form-control"></textarea>
<!--<span ng-show="astroProfileform.$submitted && astroProfileform.profileengresumetext.$error.required">
Profile Resume Text is required.
</span>-->
</div>
<label class="col-sm-1 control-label" ng-if="astroProfile.ResumeText=== null"><span class="label label-danger">Incomplete</span></label>
</div>
</div>
this code only works when checkbox is checked on load but when i checked the checkbox it will not show the div.I am new for angularjs please guide me.
I try to open div automatically if checkbox is check on load and if not then when user checked the checkbox it will show the div
AngularJs creates a child $scope inside ng-if so you should use $parent object to access the parent controller $scope.
Code example:
<label class="radio-inline" ng-if="$ctrl.astrologerLanguageDetails.IsEnglishValue === true">
English <input type="checkbox" ng-checked="true"><br /><br />
</label>
<label class="radio-inline" ng-if="!$ctrl.astrologerLanguageDetails.IsEnglishValue === true">
English <input type="checkbox" ng-model="$parent.ENchkselct" ><br /><br />
</label>

ng-show Not Showing When input is invalid

I am having trouble with form validation in AngularJS. I am trying to show a div based on whether an input is invalid. Angular is putting the correct classes on my inputs (ng-touched and ng-invalid) but it is still keeping the div with a ng-hide class.
form.html
<form id="" name="contactForm"
ng-submit="postForm()" novalidate>
<div class="form-group row">
<label for="full-name" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Name</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="text" placeholder="Jon Doe"
id="full-name" required data-ng-model="formData.name">
</div>
</div>
<!-- This is the only input implemented with the errors -->
<div class="form-group row">
<label for="phone-number" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Phone
Number</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="tel"
placeholder="(630) 555-6723" id="phone-number" required
data-ng-model="formData.phone" name="phone" ng-minlength="10"/>
</div>
<div ng-show="(contactForm.phone.$invalid && contactForm.phone.$touched) || contactForm.phone.$error.minlength">Please enter a valid phone
number.</div>
</div>
<div class="form-group row">
<label for="email" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Email</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="email"
placeholder="jon.doe#gmail.com" id="email" required
data-ng-model="formData.email" />
<div class="invalid-feedback">Please enter a valid email.</div>
</div>
</div>
<div class="form-group row">
<label class="col-2 col-form-label">Contact Method</label>
<div class="col-lg-2 col-md-3 col-xs-4">
<label class="custom-control custom-radio"> <input
id="radio1" name="email" type="radio"
class="custom-control-input" checked="checked"
data-ng-model="formData.pref"> <span
class="custom-control-indicator"></span> <span
class="custom-control-description">Email</span>
</label> <label class="custom-control custom-radio"> <input
id="radio2" name="phone" type="radio"
class="custom-control-input" data-ng-model="formData.pref">
<span class="custom-control-indicator"></span> <span
class="custom-control-description">Phone</span>
</label>
</div>
</div>
<div class="form-group row">
<label for="full-name" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Body</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<textarea rows="15" class="form-control"
placeholder="Type your message here..." id="body-text" required
data-ng-model="formData.body"></textarea>
<div class="invalid-feedback">Please enter a message here.</div>
</div>
</div>
<div class="text-center">
<button ng-disabled="contactForm.$invalid" class="btn-primary btn" type="submit">Submit</button>
</div>
</form>
</div>
angular.js
<!-- SCRIPTS -->
<script>
//form validate
var app = angular.module('contactUs', []);
app.controller('formCtrl', function($scope, $http) {
$scope.formData = {};
$scope.postForm = function() {
$('#loadingScreen').modal('show');
$http({
url : '/api/v1/contact',
method : 'POST',
data : $.param($scope.formData),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function onSuccess() {
console.log("success");
window.scrollTo(0,0);
$('#success-message').show();
}, function onError(){
console.log("error");
window.scrollTo(0,0);
$('#error-message').show();
})
.then(function() {
$('#loadingScreen').modal('hide');
})
}
$scope.formData = {};
});
</script>
Looking at other errors I made sure that the ng-show was using the formName.inputName and that the app and controller were working correctly. The button is disabled correctly when the form is invalid which leads me to believe that the controller and app are not the problem.
I tried using ng-messages which changed my phone portion of the form to
<div class="form-group row">
<label for="phone-number" class="col-lg-2 col-md-3 col-xs-4 col-form-label">Phone
Number</label>
<div class="col-lg-10 col-md-9 col-xs-8">
<input class="form-control" type="tel"
placeholder="(630) 555-6723" id="phone-number" required
data-ng-model="formData.phone" name="phone" ng-minlength="10"/>
</div>
<div ng-messages="contactForm.phone.$error" class="error" ng-if="contactForm.phone.$dirty">
<div ng-message="required">Please enter a phone number we can reach you at.</div>
<div ng-message="pattern">Please enter a valid phone number here.</div>
<div ng-message="minlength">Please enter a phone number that's atleast 10 digits</div>
</div>
</div>
Angular is still adding the correct classes to the input but it is still not displaying. I believe the ng-if is evaluating false. Oddly, when I run
{{contactForm.phone.$dirty}}
in the console it is coming back as undefined
Take a look here and you can see how I got it working. I'll break down the steps below. https://plnkr.co/edit/LJYurBObZsS6ptlVKxvP?p=preview
With the change to using ng-messages, you need to include that module in your app. I wasn't sure if you had made this change or not, but it's straightforward. Include the script for the library, and then update your modules to include ngMessages as a dependency.
var app = angular.module('contactUs', ['ngMessages']);
The second part is fixing a typo. In your html for the contact method area, you have
<label class="custom-control custom-radio">
<input id="radio2" name="phone" type="radio" class="custom-control-input" data-ng-model="formData.pref">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Phone</span>
</label>
You're reusing the name "phone" there, which is going to cause problems since you'll have two different form items with the same name. Probably change those inputs to emailPreference and phonePreference or something to be clear.
As soon as I cleaned that up, it started working. So I think you were all there, just this typo was getting you.

Select multiple radio options in angularjs issue

I want to select multiple radio options.New to angularjs.
Steps to produce the issue:
Select any country from the 1st select menu -> Choose Reason A
Select any country from the 2nd select menu -> Choose Reason C
here the above Reason A option disappears and only Reason C is selected.
i want to hold the two different reasons for different countries section.
here is the fiddle
http://jsfiddle.net/Lini7/knfsv64m/8/
var app = angular.module('myApp', []);
app.controller('myController', function ($scope) {
$scope.showReasonA = function showReasonA(checkNoTin) {
console.log("print the notin value from data",this.item.noTin);
if (!this.item.country) return false;
var selectedCountry = this.item.country.country.toLowerCase();
var fourCountries = ["cayman islands", "albania"]
var isIt = fourCountries.indexOf(selectedCountry) >= 0;
console.log("print match country val",isIt);
console.log("get checknotin value before assign",checkNoTin);
if (checkNoTin) this.item.noTin = true;
console.log("final checknotin val",checkNoTin);
return isIt;
}
});
and the view
<body>
<div ng-app="myApp">
<div ng-controller="myController">
<select name="country_0" ng-model="item.country" ng-options="" required="required" class="ng-not-empty ng-dirty ng-valid-parse ng-valid ng-valid-required ng-touched" style=""><option value="" selected="selected"></option><option label="AFGHANISTAN" value="object:835">AFGHANISTAN</option><option label="cayman islands" value="object:836">cayman islands</option><option label="ALBANIA" value="object:837">ALBANIA</option><option label="ALGERIA" value="object:838">ALGERIA</option><option label="AMERICAN SAMOA" value="object:839">AMERICAN SAMOA</option></select>
<div class="row">
<label class="checkbox">
<input type="checkbox" ng-model="item.noTin" ng-disabled="item.tin" ng-checked="showReasonA(true)" ng-required="item.noTin" name="checkboxNoTin"/>
</label><span translate="transactions.changeAddress.crs.yes.me_no_tin" style="margin-top: 10px" class="col-value"></span>
</div>
<div ng-if="item.noTin" class="row">
<div class="col padding-top-xs"><span translate="transactions.changeAddress.crs.select_reason" style="margin-bottom: 12px;" class="pol-value col-value"></span>
<div ng-if="item.country.tin == true" ng-init="item.reason = 0" class="row margin-bottom-medium">
<label class="radio-button">
<input type="radio" name="reason" ng-model="item.reason" ng-value="A" required="required"/><span class="indicator"></span><span translate="transactions.changeAddress.crs.yes.reason1"></span>
</label>
</div>
<div ng-if="!showReasonA()" class="row margin-bottom-medium">
<div class="col">
<label class="radio-button">
<input type="radio" name="reason" ng-model="item.reason" ng-value="B" required="required"/><span class="indicator"></span><span translate="transactions.changeAddress.crs.yes.reason2_title"></span>
<label class="item item-input input-margin">
<textarea ng-model="item.othersReason" ng-required="item.reason == 2" rows="5"></textarea>
</label>
</label>
</div>
</div>
<div ng-if="!showReasonA()" class="row margin-bottom-medium">
<div class="col">
<label class="radio-button">
<input type="radio" name="reason" ng-model="item.reason" ng-value="C" required="required"/><span class="indicator"></span><span translate="transactions.changeAddress.crs.yes.reason3"></span>
</label>
</div>
</div>
</div>
</div>
<select name="country_0" ng-model="item.country" ng-options="" required="required" class="ng-not-empty ng-dirty ng-valid-parse ng-valid ng-valid-required ng-touched" style=""><option value="" selected="selected"></option><option label="AFGHANISTAN" value="object:835">AFGHANISTAN</option><option label="cayman islands" value="object:836">cayman islands</option><option label="ALBANIA" value="object:837">ALBANIA</option><option label="ALGERIA" value="object:838">ALGERIA</option><option label="AMERICAN SAMOA" value="object:839">AMERICAN SAMOA</option></select>
<div class="row">
<label class="checkbox">
<input type="checkbox" ng-model="item.noTin" ng-disabled="item.tin" ng-checked="showReasonA(true)" ng-required="item.noTin" name="checkboxNoTin"/>
</label><span translate="transactions.changeAddress.crs.yes.me_no_tin" style="margin-top: 10px" class="col-value"></span>
</div>
<div ng-if="item.noTin" class="row">
<div class="col padding-top-xs"><span translate="transactions.changeAddress.crs.select_reason" style="margin-bottom: 12px;" class="pol-value col-value"></span>
<div ng-if="item.country.tin == true" ng-init="item.reason = 0" class="row margin-bottom-medium">
<label class="radio-button">
<input type="radio" name="reason" ng-model="item.reason" ng-value="A" required="required"/><span class="indicator"></span><span translate="transactions.changeAddress.crs.yes.reason1"></span>
</label>
</div>
<div ng-if="!showReasonA()" class="row margin-bottom-medium">
<div class="col">
<label class="radio-button">
<input type="radio" name="reason" ng-model="item.reason" ng-value="B" required="required"/><span class="indicator"></span><span translate="transactions.changeAddress.crs.yes.reason2_title"></span>
<label class="item item-input input-margin">
<textarea ng-model="item.othersReason" ng-required="item.reason == 2" rows="5"></textarea>
</label>
</label>
</div>
</div>
<div ng-if="!showReasonA()" class="row margin-bottom-medium">
<div class="col">
<label class="radio-button">
<input type="radio" name="reason" ng-model="item.reason" ng-value="C" required="required"/><span class="indicator"></span><span translate="transactions.changeAddress.crs.yes.reason3"></span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
To make some input as hidden you can use
<p ng-show="condition">I'm shown</p>
and this condition value should be initialized in the scope of your controller
$scope.condition=true/false
to hide an show input you can use ng-if. Its better to use ng-if for dynamic inputs . see details here
Now for your case you can use item.reason in the condition to show and hide your input .
<input type="radio" name="reason" ng-model="item.other" ng-value="C" required="required" ng-if="item.reason='object:836'" />
Finally got the solution
I just added the radio button name with index then it worked which will give different names for each group of buttons.
name='reason_{{$index}}'

How to have different values for two different sets of radio buttons?

I have a list of animals and there are 2 sets of radio buttons against each animal- extinct(y or n), habitat(land or water).
If user selects extinct as y for an animal then habitat radio buttons get disabled.
If user selects extinct as n, then habitat radio button will be enabled and user can select either land or water as habitat.
And on change of value of the radio button I call a function, where I am getting the selected value. Now the problem is for both radio buttons I get the same value ie (y or n). How to get proper values ie y or n for extinct and land or water for habitat.
here is the code.. i have modified the names.
HTML content
<fieldset>
<legend>List of Animals</legend>
<div class="row" ng-repeat=" animal in animals">
<label class="col-md-2 text-info">{{ animal }}:</label>
<label class="col-md-1 text-info"> Extinct</label>
<div class="col-md-1">
<input id="{{animal}}extinctY" type="radio" name="{{animal}}extinct" data- ng-model="value" value="{{animal}}|Y" ng-change="getExtinct(value1)"/>
</div>
<label class="col-md-1 text-info">Y</label>
<div class="col-md-1">
<input id="{{animal}}extinctN" type="radio" name="{{animal}}extinct" data-ng-model="value" value="{{animal}}|N" ng-change="getExtinct(value1)" required="required"/>
</div>
<label class="col-md-1 text-info">N</label>
<label class="col-md-1 text-info"> Habitat</label>
<div class="col-md-1">
<input id="{{animal}}habitatL" type="radio" name="{{animal}}habitat" ng-checked="{{animal}}checked" ng-model="value" value="{{animal}}|L" ng-disabled="{{animal}}disabled" ng-change="getHabitat(value)"/>
</div>
<label class="col-md-1 text-info">Land</label>
<div class="col-md-1">
<input id="{{animal}}habitatW" type="radio" name="{{animal}}habitat" ng-checked="{{animal}}checked" ng-model="value" value="{{animal}}|W" ng-disabled="{{animal}}disabled" ng-change="getHabitat(value)"/>
</div>
<label class="col-md-1 text-info">Water</label>
</div>
<br/>
</fieldset>
JS content
$scope.animals= ['Zebra', 'Dinosaur', 'Whale', 'Antilon'];
$scope.getExtinct= function getExtinct(extinct) {
alert(extinct); // Here it displays Zebra|N
};
$scope.getHabitat = function getHabitat(habitat) {
alert(habitat); // Here also it displays Zebra|N instead of Zebra|L
};
The easiest way to get around this is to make the animals. I created a plunkr to demonstrate. http://plnkr.co/edit/s45WEnCbRvBL2CRmjbut?p=preview
Then you can evaluate the ng-disabled, ng-value, etc. using the keys.
<fieldset ng-controller="AnimalCtrl">
<legend>List of Animals</legend>
<div class="row" ng-repeat=" animal in animals">
<label class="col-md-2 text-info">{{ animal.name }}:</label>
<label class="col-md-1 text-info"> Extinct</label>
<div class="col-md-1">
<input type="radio" name="{{animal.name}}extinct" ng-model="animal.extinct" value="true" />
<label class="col-md-1 text-info">Y</label>
</div>
<div class="col-md-1">
<input type="radio" name="{{animal.name}}extinct" ng-model="animal.extinct" value="false" required/>
<label class="col-md-1 text-info">N</label>
</div>
<label class="col-md-1 text-info"> Habitat</label>
<div class="col-md-1">
<input type="radio" name="{{animal}}habitat" ng-model="animal.habitat" value="land" ng-disabled="animal.extinct == 'true'" />
<label class="col-md-1 text-info">Land</label>
</div>
<div class="col-md-1">
<input type="radio" name="{{animal}}habitat" ng-model="animal.habitat" value="water" ng-disabled="animal.extinct == 'true'" />
<label class="col-md-1 text-info">Water</label>
</div>
</div>
</fieldset>

AngularJS populate textbox from array

I am facing a problem with AngularJS. I have made an application where a user can
select a value from a dropdown list. If the user presses the "add" button, then an array is created that holds all his selections. I want to populate a textbox with all these selections. I have tried ng-repeat but it creates multiple textbox with each array value. This is what I've made so far:
Controller
$scope.multiCompare= [];
// Create the function to push the data into the "multiCompare" array
$scope.newCompare = function () {
$scope.multiCompare.push($scope.compareDate);
$scope.multiComparedate = '';
};
HTML
<div class="form-group">
<label for="installation_year" class="col-sm-2 control-label">Period</label>
<div class="col-sm-4">
<select class="form-control" ng-model="compareDate" ng-options="res for res in compareDates " ng-disabled="disableFormInput()" ></select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" ng-click="newCompare()">Add</button>
</div>
</div>
<div class="form-group">
<label for="from_date" class="col-sm-2 control-label">Compare</label>
<div class="col-sm-4">
<div ng-repeat="num in multiCompare" track by $index>
<input class="form-control" type="text" ng-model="$parent.multiCompare[$index]">
<div> {{num}}</div>
</div>
</div>
The first image shows the result I'm getting when adding 2013 and 2014 and the second shows what I would like it to return.
Can someone help me through this?
Thanks in advance..
For rendering your Compare field input, you can take use of ngList directive. That will bind your comma(,) separated output directly to the input element.
Change
<label for="from_date" class="col-sm-2 control-label">Compare</label>
<div class="col-sm-4">
<div ng-repeat="num in multiCompare" track by $index>
<input class="form-control" type="text" ng-model="$parent.multiCompare[$index]">
<div> {{num}}</div>
</div>
</div>
TO
<label for="from_date" class="col-sm-2 control-label">Compare</label>
<div class="col-sm-4">
<input class="form-control" type="text" ng-model="multiCompare" ng-list/>
</div>
This could help you, Thanks.
I have managed to do what I wanted. I changed my html code to this:
<div class="form-group">
<label for="from_date" class="col-sm-2 control-label">Compare</label>
<div class="col-sm-4">
<div data-ng-repeat="num in multiCompare" track by $index>
<input class="form-control" type="text" ng-model="multiCompare" ng-list {{num}} ng-show="$last" />
</div>
</div>
</div>
And it worked!
Your ng-list suggestion was really helpful! Thank you very much!

Resources