How to select all the check boxes in nested ng-repeat - javascript

I'm trying to create a list where there are multiple select all buttons to for ng-repeat check boxes.
HTML code
<div class="col-xs-12"ng-repeat="items in testArray">
<div class="col-xs-6">
{{items.brand}}
</div>
<div class="col-xs-6 col-sm-offset-6">
<button ng-click="selectAll()">select All</button>
<div ng-repeat="i in items.form">
<input type="checkbox"/>{{i.formName}}
</div>
</div>
</div>

you can try it.this example you can manipulate it according to your need
https://plnkr.co/edit/qD7CABUF9GLoFCb8vDuO?p=preview
$scope.test=function(event){
if(event.currentTarget.checked==true)
{
var togglestatus=$scope.isAllSelected;
angular.forEach($scope.options,function(object){
object.selected=togglestatus
})
}else{
angular.forEach($scope.options,function(object){
object.selected=false
})
}
}
html:
<body ng-app="test" ng-controller="testctrl">
<label>
<input type="checkbox" ng-model="isAllSelected" ng-click="test($event)">SelectAll</label>
<div ng-repeat="option in options">
<input type="checkbox" ng-model="option.selected">checkbox</div>
</body>

Please check ngChecked directive. You need to add it to your input
<input type="checkbox" ng-checked="i.isChecked" />
and then in selectAll() method set isChecked property on every item to true.

look at code snippet given below , this will give you idea.
var app = angular.module("myApp",[]);
app.controller('demoCtrl',function($scope){
$scope.itemsArray = [{name:"Test 1",forms:[{formName:"xyz 1 "},{formName:"xyz 1 "}]},{name:"Test 2",forms:[{formName:"xyz 2 "},{formName:"xyz 1 "}]},{name:"Test 3 ",forms:[{formName:"xyz 3"},{formName:"xyz 1 "}]}];
$scope.selectAll = function(item){
for(var i =0;i < item.forms.length;i++)
{
item.forms[i].isChecked = true;
}
}
$scope.removeAll = function(item) {
for(var i =0;i < item.forms.length;i++)
{
item.forms[i].isChecked = false;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="demoCtrl">
<div ng-repeat="item in itemsArray">
<span>{{item.name}}</span>
<button ng-click="selectAll(item)"> select All </button>
<button ng-click="removeAll(item)"> Deselect All </button>
<div ng-repeat="i in item.forms">
<input type="checkbox" ng-model="i.isChecked"/>
</div>
</div>
</div>
</div>

You can simply set a variable to true like this
ng-click="selectAll = true"
and then use the ng-checked directive to set the checkbox to checked when the expression inside is true
ng-checked="selectAll"
HTML
<div class="col-xs-12"ng-repeat="items in testArray">
<div class="col-xs-6">
{{items.brand}}
</div>
<div class="col-xs-6 col-sm-offset-6">
<button ng-click="selectAll = true">select All</button>
<div ng-repeat="i in items.form">
<input type="checkbox" ng-checked="selectAll"/>{{i.formName}}
</div>
</div>
</div>

Created a fiddle, showcasing your need for requirement "select all" - http://jsfiddle.net/deeptechtons/TKVH6/
//html
<div>
<ul ng-controller="checkboxController">
<li>Check All
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</li>
<li ng-repeat="item in Items">
<label>{{item.Name}}
<input type="checkbox" ng-model="item.Selected" />
</label>
</li>
</ul>
</div>
//js
angular.module("CheckAllModule", [])
.controller("checkboxController", function checkboxController($scope) {
$scope.Items = [{
Name: "Item one"
}, {
Name: "Item two"
}, {
Name: "Item three"
}];
$scope.checkAll = function () {
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.Items, function (item) {
item.Selected = $scope.selectedAll;
});
};
});

Related

ng-class to select button based on condition in ng-repeat

I have below code where I am displaying buttons based on array values. I want to select button based on a condition which checks if it matches with another array values. I have added an ng-class to check i in array1 loop matches listApi but couldn't come up with correct logic and get it tow work. Need help please
<label ng-repeat="i inn array1 track by $index">
<label class="btn-primary" ng-click="array1Selection()">
<span ng-class="{'btn-primary': i.name === listApi[0].name}"></span>
{{i.name}}
</label>
</div>
</label>
Your span tag is empty and I think you should put {{i.name}} inside that. also you should not add class 'btn ...' to your label. Hope this code helps you.
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.array1 = [{
id: 1,
name: "abc"
}, {
id: 1,
name: "xyz"
}];
$scope.listApi = [{
id: 2,
name: "xyz"
}];
$scope.existInList = function(itm) {
let x = $scope.listApi.findIndex(it => {
return it.name == itm.name
});
return x == -1 ? false : true;
}
});
.exists {
color: green
}
.noexists {
color: red
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<h2>Add class to existing items and others</h2>
<label ng-repeat="i in array1">
<div data-toggle="buttons">
<label>
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span ng-class="{true: 'exists', false: 'noexists'}[existInList(i) === true]">
{{i.name}}
</span>
</div>
</label>
</div>
</label>
<h2>Show only if exists in list</h2>
<label ng-repeat="i in array1">
<div data-toggle="buttons">
<label ng-if="existInList(i)">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span>
{{i.name}}
</span>
</div>
</label>
</div>
</label>
</body>
</html>
I'm not 100% sure JS' find will work inline in Angular but is so...
<label ng-repeat="i inn array1 track by $index">
<div data-toggle="buttons">
<label class="btn btn-w-m btn-primary" ng-click="array1Selection()">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span nng-class="btn btn-w-m btn-primary: listApi.find(a => a.name === i.name)"></span>
{{i.name}}
</div>
</label>
</div>
</label>
A simple modification
var app = angular.module("app", []);
app.controller("MainCtrl", function($scope) {
$scope.array1 = [{ id: 1, name: "abc" }, { id: 1, name: "xyz"
}];
$scope.listApi = [{ id: 2, name: "xyz" }];
$scope.foundInApiList = function(name) {
for(var i = 0; i < $scope.listApi.length; i++)
if($scope.listApi[i].name == name)
return true;
return false;
}
});
.exists {
color: green
}
.noexists {
color: red
}
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<label ng-repeat="i in array1 track by $index">
<div data-toggle="buttons">
<label class="btn btn-w-m btn-primary" ng-click="array1Selection()">
<div class="itemcontent">
<input type="checkbox" name="array1Select" />
<span class="btn btn-w-m btn-primary" ng-class="{true: 'exists', false: 'noexists'}[foundInApiList(i.name)]">{{i.name}}</span>
</div>
</label>
</div>
</label>
</body>
</html>

Adding more value to class to filter

This is my main script, that filters div by checkboxes
function change(){
var checkboxes = document.getElementsByClassName('checkbox');
var chekboxInputs = Array.from(checkboxes).map(a => a.querySelector('input'));
var allAreUnselected = chekboxInputs.every(function(elem){
return !elem.checked;
});
if(allAreUnselected){
chekboxInputs.forEach(function(input){
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item){
item.style.display = 'block';
});
});
}
else {
chekboxInputs.forEach(function(input){
Array.from(document.querySelectorAll("." + input.getAttribute("rel"))).forEach(function(item){
item.style.display = input.checked ? 'block' : 'none';
});
});
}
}
change();
This is my html file. In this html there are checkboxes and dives
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada" onchange="change()"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china" onchange="change()"/>China</label>
</div>
</div>
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
</div>
But the script filters only one value(in my case - city). How can I add another filters to class of div. For example
<div class="checkbox">
<label><input type="checkbox" rel="india" onchange="change()"/>India</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="programming" onchange="change()"/>Programming</label>
</div>
by the adding another value to class
<div class="india programming">...</div>
Adding multiple CSS classes could work, but your current code will overwrite a previous setting of style.display making it sometimes go from none to block, even though the none setting was the right setting.
Here is the code you could use, based on the first example you gave, and an additional result that has both classes "canada" and "china":
function change(){
let results = Array.from(document.querySelectorAll('.result > div'));
// Hide all results
results.forEach(function (result) {
result.style.display = 'none';
});
// Filter results to only those that meet ALL requirements:
Array.from(document.querySelectorAll('.filter input[rel]:checked'), function (input) {
const attrib = input.getAttribute('rel');
results = results.filter(function (result) {
return result.classList.contains(attrib);
});
});
// Show those filtered results:
results.forEach(function (result) {
result.style.display = 'block';
});
}
change();
<div class="filter">
<div class="checkbox">
<label><input type="checkbox" rel="canada" onchange="change()"/>Canada</label>
</div>
<div class="checkbox">
<label><input type="checkbox" rel="china" onchange="change()"/>China</label>
</div>
</div>
<div class="result">
<div class="canada">
<h1>Canada</h1>
<h2>Jason</h2>
</div>
<div class="china">
<h1>China</h1>
<h2>Ni</h2>
</div>
<div class="canada china">
<h1>China and Canada</h1>
<h2>Ni Jason</h2>
</div>
</div>
Note that I assume the rel attribute can only reference one CSS class.

How to get checked checkboxes using Semantic UI and AngularJS?

Since I am using Semantic UI for checkboxes, the <input> tag is wrapped with a <div class="ui checkbox"> and what happens is when the box is checked, it just adds the class checked.
<div class="field" ng-repeat="animal in animals">
<div class="ui checkbox">
<input class="hidden" tabindex="0" type="checkbox" value="{{animal.id}}" ng-model="animal.selected">
<label>{{animal.name}}</label>
</div>
</div>
How do I get the id or value of the selected checkboxes using AngularJS? Thank you.
You can have a function in your controller
$scope.getAnimal= function(){
angular.forEach($scope.animals, function(animal){
if (animal.selected) do smth here...
})
}
You can use Array.prototype.filter() method to get only the selected objects.
Here's a demonstration:
angular.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.animals = [];
for (var i = 0; i <= 5; i++) {
$scope.animals.push({
"id": Math.floor(Math.random() * 310),
"name": "Name " + Math.floor(Math.random() * 420),
"selected": i % 2 === 0 ? true : false
});
}
$scope.selected = [];
$scope.show = function() {
$scope.selected = $scope.animals.filter(function(value) {
return value.selected;
});
}
});
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div class="field" ng-repeat="animal in animals track by $index">
<div class="ui checkbox">
<input id="checkbox{{$index}}" class="hidden" tabindex="0" type="checkbox" value="{{animal.id}}" ng-model="animal.selected">
<label for="checkbox{{$index}}" ng-bind="animal.name"></label>
</div>
</div>
<hr>
<button type="button" value="show" ng-click="show()">Show selected tems</button>
<pre ng-bind="selected | json"></pre>
</body>
</html>

Dynamic angular models?

Okay, so I am building a fake dish builder for a restraunt. I have a form that includes everything you need to build it, and the only thing I am having trouble with is the ingredient list. Here is my HTML:
<div class="icheckbox" ng-repeat="ing in ingredientList">
{{ing}}
<input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)"/>
<input type="number" name="more" ng-model="ings.ing.more" placeholder="price for extra"/>
<input type="number" name="less" ng-model="ings.ing.less" placeholder="price for less/none"/>
</div>
and here is the (relevent) JS:
$scope.ings = {};
$scope.ingredientList = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
$scope.addIngredient = function(which){
$scope.ings[which] = which;
}
$scope.makeItem = function(item){
item.ingredients = $scope.ings;
console.log(item);
ItemService.createItem(item)
.then(handleRes, handleRes);
}
As I'm sure you guessed, when I am trying to check a box for a specific ingredient and add the price modifiers for more or less of that specific ingredient, it modifies the price for all ingredients in the list. E.g., I can't have individual modifiers because of the model. I know this is a problem with the model, but how can I rewrite my code to accomplish what I'm doing?
for those reading this after the correct answer has been chosen, see the fiddle located here to see a more accurate HTML of what I was working with. By the way, the fiddle doesn't entirely work (for reasons I don't know, but I rarely use JSFiddle), but it is super easy to understand what I was trying to do if you see it I think. http://jsfiddle.net/Lrpjwyrg/13/
i a bit change your fiddle:
first, use ng-model="ings[ing].more" and ng-model="ings[ing].less".
second, save object in ings array instead of just string
$scope.addIngredient = function(which) {
$scope.ings[which] = {
name: which
};
}
angular.module('CpCtrl', []).controller('ControlPanelCtrl', [
'$scope',
function($scope) {
$scope.message = '';
$scope.inglist = ['lettuce', 'tomatoe', 'steak', 'pulled pork', 'green onion', 'red onion', 'mozarella', 'cheddar', 'bacon bits', 'chicken'];
$scope.sauceList = ['bbq', 'ranch', 'nacho cheese', 'yum sauce'];
$scope.ings = {};
$scope.addIngredient = function(which) {
$scope.ings[which] = {
name: which
};
}
$scope.makeItem = function(item) {
item.ingredients = $scope.ings;
console.log(item);
}
}
]);
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container-fluid text-center" ng-app="CpCtrl" ng-controller="ControlPanelCtrl">
<div class="row">
<div class="page-title text-center">
<h3> Welcome</h3>
</div>
</div>
<div class="row">
<div class="jumbotron">
<h2> Make Item </h2>
<form>
<div class="form-group">
<label for="itemname">Item Name</label>
<input class="form-control" type="text" ng-model="item.itemname" id="itemname" />
</div>
<div class="form-group">
<label for="itemdescription">Item Description</label>
<textarea class="form-control" ng-model="item.itemdescription" id="itemdescription"></textarea>
</div>
<!-- pizza, sub or spud -->
<label>
<div class="icheckbox_square-green">
<input type="checkbox" name="pizza" ng-model="item.pizza" ng-click="setBase()" />Pizza
</div>
</label>
<label>
<div class="icheckbox">
<input type="checkbox" name="sub" ng-model="item.sub" ng-click="setBase()" />Sub
</div>
</label>
<label>
<div class="icheckbox">
<input type="checkbox" name="spud" ng-model="item.spud" ng-click="setBase()" />Spud
</div>
</label>
<!-- end -->
<!-- prices -->
<div class="form-group">
<label for="spud-price" ng-if="item.spud">Spud Price</label>
<input class="form-control" type="number" name="spud-price" ng-if="item.spud" id="spud-price" ng-model="item.price.spud" />
</div>
<div class="form-group">
<label for="pizza-price" ng-if="item.pizza">Pizza Price</label>
<input class="form-control" type="number" name="pizza-price" ng-if="item.pizza" ng-model="item.price.pizza" />
</div>
<div class="form-group">
<label for="sub-price" ng-if="item.sub">Sub Price</label>
<input class="form-control" type="number" name="sub-price" ng-if="item.sub" ng-model="item.price.sub" />
</div>
<!-- end -->
<!-- ingredients -->
<div ng-repeat="ing in inglist">
{{ing}}
<input type="checkbox" name="{{ing}}" ng-click="addIngredient(ing)" />
<input type="number" name="more" ng-model="ings[ing].more" placeholder="price for extra" />
<input type="number" name="less" ng-model="ings[ing].less" placeholder="price for less/none" />
</div>
<!-- end -->
<!-- picture -->
<div class="form-group">
<label for="picture">Add Picture(s)</label>
<input type="file" name="picture" />
</div>
<!-- end -->
<a class="btn btn-primary" ng-click="makeItem(item)">Create</a>
</form>
</div>
</div>
<!-- end item creation -->
I don't know if this is the right answer. But i think it is close to what you want.
angular.module('app', [])
.controller('cntrl', function ($scope) {
$scope.ingredientList = [{
name: 'lettuce',
count: 0,
price: 23,
selected: false
}, {
name: 'tomatoe',
count: 0,
price: 87,
selected: false
}, {
name: 'steak',
count: 0,
price: 98,
selected: false
}, {
name: 'pulled pork',
count: 0,
price: 292,
selected: false
}];
$scope.setItOne = function (idx) {
if ($scope.ingredientList[idx].count < 1) {
$scope.ingredientList[idx].count = 1;
}
updateSelectedingredients();
};
function updateSelectedingredients() {
$scope.selectedingredients = $scope.ingredientList.filter(function (item) {
return item.selected;
});
}
$scope.getTotal = function(){
var total = 0;
( $scope.selectedingredients || []).forEach(function(item){
total = total + item.count * item.price;
});
return total;
};
$scope.makeItem = function () {
alert(JSON.stringify($scope.selectedingredients));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="cntrl">
<div class="icheckbox" ng-repeat="ing in ingredientList">{{ing.name}}
<input type="checkbox" name="{{ing}}" ng-model="ing.selected" ng-change="setItOne($index)" />
<button ng-click="ing.count = ing.count + 1">Up</button>
<button ng-click="ing.count = ing.count - 1" ng-disabled="ing.count < 1">Down</button>
| {{ing.count}} x {{ing.price | currency}} = {{ing.count * ing.price | currency}}
</div>
<hr/>
<div>Selected items
<ul>
<li ng-repeat="item in selectedingredients">{{item.name }} x {{item.count}} -> {{item.count}} x {{item.price | currency}} = {{item.count * item.price| currency}}</li>
</ul>
<b>Total: {{ getTotal() | currency}}</b>
</div>
<button ng-click="makeItem()">Make Item</button>
</div>
</div>

adding a textbox element dynamically to a form by AngularJS

How can we add a textbox element to a form dynamically using AngularJs. For example in this case, I have a text and textbox which I want to add one other of this pair by clicking on a button using AngularJs.
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<div ng-hide="editorEnabled" ng-click="editorEnabled=true">
{{title}}
</div>
<div ng-show="editorEnabled">
<input ng-model="title">
<button href="#" ng-click="editorEnabled=false">Done editing</button>
</div>
</div>
</div>
<div>
<input type="text" placeholder="Enter answer">
</div>
I implemented it myself. You could dynamically add an element by using ng-repeat in a
<li ng-repeat="elemnt in questionelemnt">
Here it is the Demo: fiddle
js file
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}, {id: 'choice3'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice' +newItemNo});
};
$scope.showAddChoice = function(choice) {
return choice.id === $scope.choices[$scope.choices.length-1].id;
};
html
<div class="form-group" data-ng-repeat="choice in choices">
<label for="choice" ng-show="showChoiceLabel(choice)">Choices</label>
<button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another choice</button>
<input type="text" ng-model="choice.name" name="" placeholder="Enter a restaurant name">
</div>
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ol>
<li ng-repeat="element in elements">
<input type="text" ng-model="element.value"/>
</li>
</ol>
<br/>
<b>Click here to add Textbox:</b><br/><input type="button" value="New Item" ng-click="newItem()"/>
<br/>
<br/>
<b>Click here to see ng-model value:</b><br/>
<input type="button" value="submit" ng-click="show(elements)">
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var counter=0;
$scope.elements = [ {id:counter, value : ''} ];
$scope.newItem = function(){
counter++;
$scope.elements.push( { id:counter,value:''} );
}
$scope.show=function(elements) {
alert(JSON.stringify(elements));
}
});
</script>
</body>
</html>

Categories

Resources