Select all if all checkboxes are selected, angular js - javascript

On my page I have angular ui accordion, inside of each panel, I'm rendering list with items and checkboxes, also I have checkbox "select all".
For selection method and logic I used this resource. In this resource logic seems working, but however I'm putting this logic to my code, it stops working.
What I want to achieve is when all checkboxes are selected, checkbox "select all" has been selected automatically, and if some of checkboxes is unselect, checkbox "select all" has to be unselect as well.
I have tried multiple suggestions provided here, here, here, but in the end I'm getting the same result.
I appreciate if somebody could help me to resolve my problem.
$scope.categories = [
{
id: 1,
name: "category 1"
},
{
id: 2,
name: "category 2"
},
{
id: 3,
name: "category 3"
}
]
$scope.selectedAll = false;
$scope.selectAll = function(array) {
$scope.selectedAll = !$scope.selectedAll;
angular.forEach(array, function(item) {
item.Selected = $scope.selectedAll;
});
};
$scope.checkIfAllSelected = function(array) {
$scope.selectedAll = array.every(function(item) {
return item.Selected == true
})
};
html
<div>
<div class="row" ng-class="{'selected': selectedAll, 'default': !selectedAll}">
<div>Select all
<input type="checkbox"
ng-model="selectedAll" ng-click="selectAll(categories)" >
</div>
</div>
<div class="row" ng-repeat="item in categories | orderBy : 'id'" ng-class="{'selected': item.selected, 'default': !item.selected}">
<div > {{ item.name }}
<input type="checkbox"
ng-model="item.Selected" ng-click="checkIfAllSelected(categories)"
>
</div>
</div>
This is my plunker

Please take a look at this fork of your plunker: https://plnkr.co/edit/OW3F1VMke9iLuNkt5p3o?p=preview
Two things:
1. It's a good practice to create an object to your view model (you can find it under the name model in the plunker $scope.model. This will solve 2 way data binding issues.
2. I have changed the ng-click to ng-change (this is not part of the solution though - its just more correct in my opinion).
Please let me know if you need more clarifications.

Related

Create inputs as array in angular form

Tried my level best please help me out..
I am making an angular dynamic form with a form splitting into total of three parts in which the two parts were made already. Now I am making part three which will be generated by selecting an option from dropdown...
Even those part also is done...
But I am unable to make a form array in it... As I am new in angular please help me.
HTML:
Form part 3 will be here which will be array
<select multiple (change)="changeEvent($event)">
<option *ngFor="let opt of persons" [value]="opt.key">{{opt.value}}</option>
</select>
<div *ngFor="let item of array">
{{item.value}} is the parent
<div *ngFor="let child of item.templateChild">
{{child.property_name}}
<div *ngFor="let partThree of questionsParthree">
<ng-container>
<app-question [question]="partThree" [form]="formPartThree"></app-question>
</ng-container>
</div>
</div>
</div>
Select Box change event:
changeEvent(e) {
if (e.target.value == 1) {
this.array = [];
this.array.push(
{
key: 1, value: "Template one",
templateChild: [
{ property_name: "Property one" },
{ property_name: "Property two" }
]
}
);
let propertiesArray = [];
this.array.forEach(element => {
element.templateChild.forEach(data => {
propertiesArray.push(
{
key: data.property_name,
label: data.property_name,
"elementType": "textbox",
"type": "text"
}
)
});
});
this.questionsPartThree = this.service.getQuestions(propertiesArray);
this.formPartThree = this.qcs.toFormGroup(this.questionsPartThree);
this.formJoin = new FormGroup({ form1: this.form, form2: this.formPartTwo, form3: this.formPartThree });
}
}
Continuation like part 1 and 2..
I have posted the code related to creating the form array alone..
Updated Stackblitz https://stackblitz.com/edit/angular-x4a5b6-mnyifs
Here if we select any option then you will get the input boxes with values..
I would like to create array with it like,
If we select the first option Template One, Output expected is exactly as like
"templateChild" : [
{"property_one": "", "property_two":""}
]
So the final output of whole form going to be if i select Template One and also Template Two from select box (as select box is multi select),
{
"form1": {
"project_name": "",
"project_desc": ""
},
"form2": {
"property_one": "",
"property_two": ""
},
"template_details" : [
{ "template_name": "Template One",
"templateChild" : [{"property_one": "", "property_two":""}]
},
{ "template_name": "Template Two",
"templateChild" : [{"property_three": "", "property_four":"",
"property_five":""}]
}
]
}
Have a work around in the demo i have provided and give me a better solution..
Kindly please help me to create a form as like the above when we select an option from dropdown.. If i am wrong in my approach also please correct me..
If i finish this third part then everything will get alright any angular technical expert please help me..
Taking too long please help me out..
You can dynamically change an AbstractController inside a FormGroup using the setControl() method.
Add an empty form3 part for the moment
this.form3 = new FormGroup({});
this.formJoin = new FormGroup({ form1: this.form, form2: this.formPartTwo, form3: this.form3 })
When selecting an item, generate a new FormGroup according the form you create.
if (e.target.value == 1) {
this.array = [];
this.form3 = new FormGroup({'Property one': new FormControl('insert whatever you want')});
this.formJoin.setControl('form3', this.form3);
You should be able to do something what that start!

how to show dropdown box after selecting any one of checkbox created in loop angular js

I am new to angular js programming so please excuse me if my question is naive.
I am populating a list of checkboxes depending upon values inside a json object.
I am using ng-repeat to iterate through the list of keys & values received & display the check box. When each of the check box is clicked I am making a server call to get relevant data. The data I receive should be populated in a dropdown list only when it is clicked & the dropdown should disappear on un-click. I want to capture the dropdown selected option after the user selects it.
I am stuck as to how to get it.
My code for reference :
HTML :
<div class="container" ng-controller="OptionsController" >
<div ng-repeat="(key, value) in options" ng-if="value === 'text'">
<!-- {{key}} : {{value}}-->
<input type="checkbox" ng-click="getDistinct(key)"/>
<label>{{key}}
</label>
<div class="animate-show">
<select id="selector" ng-model="QueryFormData.Graph.selected">
<option ng-repeat="name in QueryFormData.Graph.options"
ng-value="name">{{name}}</option>
</select>
</div>
</div>
</div>
Controller code :
myApp.controller('OptionsController', ['$scope', '$http', '$location', 'datashare',
function($scope, $http, $location, datashare) {
//$scope.options = datashare.jsonData;
$scope.options = {
"_id": "571a0fcfaa6d92581ec99b2e",
"Name": "text",
"isstring": "text",
"value1": "number",
"value": "number",
"status": "text",
"ItantaTime": "time"
};
$scope.keyArr = [];
$scope.QueryFormData = {
Graph: {
options: [
'Line Graph'
],
selected: 'Line Graph'
},
displayValue: ''
};
$scope.getDistinct = function(key) {
if ($scope.keyArr.indexOf(key) == -1) {
$scope.keyArr.push(key);
var ServerAddr = "http://localhost:2000/getDistinct/" + key;
console.log("Server Addr :" + ServerAddr);
$http.get(ServerAddr, {
headers: {
'Content-Type': 'application/json'
}
})
.success(function(result) {
console.log(result);
})
.error(function(data, status) {
console.log(data)
});
}
console.log("changed : " + key);
};
}
]);
With current code I am seeing all the dropdowns at once. I want to show the dropdowns as a toggle functionality on check box selection.
Any help is highly appreciated.
First, you don't need ng-if. Use the built-in filter:
<div ng-repeat="(key, value) in options" ng-if="value === 'text'">
Can be
<div ng-repeat="(key, value) in options | filter: { value: 'text' }">
For your filtering problem, you can again use the filter in select elements to only get the dropdown values you want. Your JSON response must have a filterable property though... So, please post your JSON.
You use it like this:
<select ng-options="item.key as item.name for item in collection| filter:{ someProperty: true }">

AngularJS: View is updated properly but not the model

I have a problem when implementing a nested list in Angular: the view gets updated properly but, on the other side, the code is not updated on change.
I think it will be much clearer with the code:
_this.categories = injections.map(function (category) {
return {
title: category.get('title'),
object: category,
criteria: category._criteria.map(function (oneCriteria) {
return {
object: oneCriteria,
type: oneCriteria.get("type"),
min: _this.range(oneCriteria.get("range")).min,
max: _this.range(oneCriteria.get("range")).max,
key: oneCriteria.get("key"),
value: _this.range(oneCriteria.get("range")).min,
defaultValue: _this.range(oneCriteria.get("range")).min,
selected: false
}
})
}
});
_this.category = _this.categories[0];
_this.job = {
title: '',
description: '',
salaryAmount: 0,
salaryTimeUnit: _this.salaryTimeUnits[0],
category: _this.category.object,
criteria: _this.category.criteria,
location: {latitude: 48.137004, longitude: 11.575928}
};
So and, very quick here is my HTML:
<div ng-repeat="category in controller.categories">
<input type="radio" name="group" ng-value="category.object.get('title')" id="{{category.object.get('title')}}"
ng-checked="controller.category == category" ng-click="controller.category = category">
{{category.title}}
</div>
<br>
Criteria:
<div ng-repeat="criterium in controller.category.criteria">
<div class="row vertical-align">
<div class="col-xs-9">
<span ng-click="criterium.selected = !criterium.selected"
ng-class="['list-group-item', {active:criterium.selected == true}]">{{criterium.key}}</span>
</div>
</div>
</div>
The problem is the following: the value are getting updated in the view (when you click on a radio button on the category, you see the corresponding criteria(s)). But the job is for one reason that I ignore not updated although it has the same reference as the HTML (a reference to this category.criteria).
Did I miss something?
controller.job.criteria is still just a reference to controller.categories[0]. Your code should successfully update controller.category to point at whichever category you clicked on, but that does not also update the reference in your job data structure.
What you want to do is make your ngClick event a bit more robust, i.e.:
<input type="radio" ng-click="controller.updateCategory(category)" />
and then in your js:
_this.updateCategory = function (category) {
_this.category = category;
_this.updateJob(category);
};
_this.updateJob = function (category) {
_this.job.category = category.object;
_this.job.criteria = category.criteria;
};
This will update the references in your job to match the new jazz.
I would, however, recommend leveraging ngModel and ngChange in your radios instead. Like:
<input type="radio" ng-model="controller.category" ng-value="category" ng-change="updateJob(category)" /> {{category.title}}

Radio buttons in multiple nested ng-repeats (angular + JSON)

I want to replace tags with radio buttons inside ng-repeats with angular and json. I display a list of products that have sub products. I would like to be able to put a radio button beside each sub product (eg. Product1-Type1) and group them by the parent product code (eg. Product1) If a user selects a sub product, the "Selected" value would be set to true and the other sub products would be set to false. And also call the displayFullPricing(prices) function.
Here is the code used to display the json (working)
<div ng-repeat="product in groups.Products">
<h3>{{product.Code}}</h3>
<div ng-repeat="prices in product.Prices">
{{prices.Code }} - {{prices.monthly.RetailPrice}}
<a ng-click="displayFullPricing(prices)">select</a>
</div>
</div>
And the json I am using...
{
"ID":"",
"Groups":[
{
"Products":[
{
"Code":"Product1",
"Prices":[
{
"Code":"Product1-Type1",
"Monthly":{
"RetailPrice":2,
"MinimumPrice":4
},
"Selected":false
},
{
"Code":"Product1-Type2",
"Monthly":{
"RetailPrice":5,
"MinimumPrice":2
},
"Selected":false
}
]
},
{
"Code":"Product2",
"Prices":[
{
"Code":"Product2-Type1",
"Monthly":{
"RetailPrice":7,
"MinimumPrice":3
},
"Selected":false
},
{
"Code":"Product2-Type2",
"Monthly":{
"RetailPrice":2,
"MinimumPrice":8
},
"Selected":false
}
]
}
]
}
]
}
Could anyone help me achieve this? I had tried moving ng-click into a radio button but it didnt work. Many thanks
Here is plunker for you.
Key thing is giving same name for radio groups so I give name with using their parent product.
<input type="radio" name="group-{{product.Code}}" ng-model="subProduct.Selected">{{subProduct.Code}}
for function call you can use ng-click.
<input type="radio" ng-click="displayFullPricing()" name="group-{{product.Code}}" ng-model="subProduct.Selected">{{subProduct.Code}}

Nested ng-option inside angular ng-repeat

Im currently trying to nest a <select> inside a div with a ng-repeat
something like this:
<li ng-repeat="item in items >
<div class="row">
<div class="col-xs-7">
<span ng-bind="item.Name"></span>
</div>
<div class="col-xs-4 modal-body--ul--li__dropdown_container">
<select ng-model="typemodel" >
<option ng-repeat="usertype in item.userGroups"></option>
</select>
</div>
<div class="col-xs-1">
<a ng-click="add(item)"></a>
</div>
</div>
</li>
In the controller im adding the item to a new list with selected items. I also want to add the value from the dropdown as a new value to the list in the controller.
$scope.add = function (item) {
//New value with the value from the dropdown
item.recipientType = typemodel;
$scope.selected.push(item);
};
The list :
$scope.items = [
{
"Name":"Name1",
"userGroups":[
{ "type": "gruop1" },
{ "type": "gruop2" },
{ "type": "group3" }
]
},
{
"Name":"Name2",
"userGroups":[
{ "type": "gruop1" },
{ "type": "gruop2" },
{ "type": "group3" }
]
}
]
In short i need the selected value from the dropdown when i hit the "add", the value of the current typemodel.
This is how it looks now, but it dont work. I know i have to get the correct model and maybe track the items list by $index, but after searching the web the whole day for a solution, im still stuck!
All help is appreciated.
-Thanks!
ps. please comment if something is missing from the question, or something more is needed to solve this.
First, change your dropdown list to
<select ng-options="usertype in item.userGroups" ng-model="item.recipientType">
Then when you trigger the add function, item's property recipientType is already set.
$scope.add = function (item) {
console.log(item.recipientType);
$scope.selected.push(item);
};

Categories

Resources