How to check/uncheck all check boxes using AngularJS? - javascript

I'm new in AngularJS and trying to achieve check/uncheck all check boxes by clicking "toggle" button, which is styled by bootstrap.
Markup:
<button id="toggle" class="btn btn-link btn-mini" ng-click="setActionTypesAllCheck()">Check all</button>
<div class="row-fluid" ng-repeat="at in actionsQuery.actionTypes">
<div class="checkbox">
<label><input type="checkbox" ng-model="at.checked">{{at.Description}}</label>
</div>
</div>
JavaScript:
$scope.setActionTypesAllCheck = function () {
$.each($scope.actionsQuery.actionTypes, function (i, cb) {
cb.checked = !cb.checked;
});
};
At this moment the code in JavaScript checks and unchecks all check boxes, but it doesn't take into account if some of them was manually checked/unchecked, which means it doesn't work properly.
So, I need to check all check boxes by clicking "toggle" button and change its name to "Uncheck all" no matter if some of check boxes is checked or not and vice versa, that is to uncheck all check boxes and change its name to "Check all" no matter if some of check boxes is checked or not.

var app = angular.module("app", []);
function MainCtrl() {
var vm = this;
vm.message = "Welcome";
vm.actionsQuery =
{
actionTypes: [
{
checked: true,
Description: "Jon"
}, {
checked: false,
Description: "Bon"
}, {
checked: false,
Description: "Tim"
}
]
};
vm.selected = function() {
}
vm.checkoxesState = true;
vm.UpdateCheckboxes = function() {
angular.forEach(vm.actionsQuery.actionTypes, function(at) {
at.checked = vm.checkoxesState;
});
vm.checkoxesState = !this.checkoxesState
};
}
angular.module("app").controller("MainCtrl", MainCtrl);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">
<body ng-controller="MainCtrl as vm">
<div class="container">
<h3>{{vm.message}}</h3>
<form>
<button id="toggle" class="btn btn-link btn-mini" ng-click="vm.UpdateCheckboxes()">
<span ng-show="vm.checkoxesState"> Check all </span>
<span ng-hide="vm.checkoxesState"> Uncheck All </span>
</button>
<div class="row-fluid" ng-repeat="at in vm.actionsQuery.actionTypes">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="at.checked">{{at.Description}}</label>
</div>
</div>
</form>
</div>
</body>
</html>

I have been using this directive for checkboxes. Its simple and it has examples that you need.

Related

First checkbox should be checked in ng-repeat if button clicked

Hi all I am new to angularjs could anybody help me please? All what I need when I click a button the first checkbox in ng-repeat list to be checked. Am I doing anything wrong? Here is my code:
Checkbox
<fieldset class="top5">
<legend title="Categories"><span class="info blackLabelUpper"><b>Dish Categories</b><span class="TextCtrlReqBgImage"> </span></span></legend>
<span class="checkbox-list" ng-repeat="dishType in dishTypes">
<input type='checkbox' ng-click="toggleDishType(dishType)" ng-model="dishType.checked" value="{{dishType}}" ng-checked="selectedDish.Type.indexOf(dishType) > -1">
{{dishType}}<br />
</span>
</fieldset>
Button
<kendo-button id="btnNewDish" class="k-primary" ng-click="onNewDishClick(true)">
<i class="fa fa-plus fa-lg" aria-hidden="true"></i>New Dish
</kendo-button>
Function
scope.onNewDishClick = function (showNewDIshMessage) {
scope.dishTypes[0].dishType = true;
}
When you use ng-model on your inputs you don't need to use value to get result because ng-model save changes on self.
Feel free to ask question, and this sample maybe helps you.
var app = angular.module("app", []);
app.controller('ctrl', function($scope){
$scope.items = [
{somthing: false, title: 'a'},
{somthing: false, title: 'b'},
{somthing: false, title: 'c'},
{somthing: false, title: 'd'},
{somthing: false, title: 'e'}
]
$scope.checkAll = function(){
angular.forEach($scope.items, function(item){
item.somthing = !item.somthing;
});
}
$scope.checkFirstItem = function(){
$scope.items[0].somthing = !$scope.items[0].somthing;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<ul>
<li ng-repeat="item in items">
<input type="checkbox" ng-model="item.somthing">
{{item.somthing}}
{{item.title}}
</li>
</ul>
<button ng-click="checkAll()">check all</button>
<button ng-click="checkFirstItem()">check first item</button>
</div>
<div ng-repeat="restorent_type in restaurant_types" style="margin:5px;" class="col col-offset-10">
<label class="item item-radio radio-label {{restorent_type.RESCOD}}">
<input type="checkbox" name="group" ng-model="restorent.types" value="{{restorent_type.RESCOD}}" ng-click="filters.RESCOD = restorent_type.RESCOD" ng-checked="$first">
<div class="item-content">
{{restorent_type.RESCOD}}
</div>
<i class="radio-icon ion-checkmark"></i>
</label>
</div>
Or you can use the :
ng-model="dishType.checked" ng-init="dishType.checked=true"
I think the Function definition should be like this :
scope.onNewDishClick = function (showNewDIshMessage) {
scope.dishTypes[0].checked = true;
}

checkboxes are not displayed inside ng repeat angularjs

I want to display checkboxes inside ng repeat. The checkboxes are not displayed. The checkboxes are not displayed at all. I am not understanding what the misatke is. Here is the code -
<div class = "col s4">
<form ng-submit="$ctrl.todoAdd()">
<input type="text" ng-model="$ctrl.todoInput" size="50" placeholder="Add New">
<input type="submit" value="Add New">
</form>
<br>
<div ng-repeat="x in $ctrl.todoList">
<input type="checkbox" ng-model="x.done"> <span ng-bind="x.todoText"></span>
</div>
<p><button ng-click="$ctrl.remove()">Remove marked</button></p>
</div>
And the javascript code-
angular.
module('dashboard').
component('dashboard', {
templateUrl: 'dashboard/dashboard.html',
controller: ['$routeParams','$http',
function dashboardController($routeParams,$http) {
this.todoList = [{todoText:'Clean House', done:false}];
this.todoAdd = function() {
this.todoList.push({todoText:this.todoInput, done:false});
this.todoInput = "";
};
this.remove = function() {
var oldList = this.todoList;
this.todoList = [];
angular.forEach(oldList, function(x) {
if (!x.done) this.todoList.push(x);
});
};
//Rest of the controller code
}
]
});
You need to have empty dependencies passed to your module while declaring,
change it as,
angular.
module('dashboard',[]).
DEMO
var app = angular.module('myFirstApp', []);
app.controller('myCtrl', function () {
this.todoList = [{
"todoText": "run today",
"done": false
},
{
"todoText": "read today",
"done": false
}];
});
<html>
<head>
<title>My First AngularJS App</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<h1>My First AngularJS App</h1>
<div ng-app="myFirstApp" ng-controller="myCtrl as ctrl">
<div ng-repeat="x in ctrl.todoList">
<input type="checkbox" ng-model="x.done"> <span ng-bind="x.todoText"></span>
</div>
</div>
</body>
</html>

Check All checkbox function inside a modal

If user clicks 'add data' a modal opens, I have individual checkboxes for data1,data2,data3,data4. I also have a check all checkbox. If user clicks this, it should be able to select all above 4, if clicks again, it should deselect all. Also, once selected, the value of 'Select All' should change to 'Deselect All'
Code:
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-body">
<label><input type="checkbox" ng-model="checkboxModel.value1"> Data1</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value2"> Data2</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value3"> Data3</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value4"> Data4</label><br/>
<label><input type="checkbox" ng-model="checkboxModel.value5">Select All</label><br/>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
<button type="button" class="btn btn-default" ng-click="open()">Add data</button>
</div>
Can someone let me know how to achieve this. I saw a lot of posts online but each had ng-repeat for the first 4 checkboxes. Mine is without using ng-repeat. Can someone please advise.
I have the following plunker: http://plnkr.co/edit/nSCGJzj1zG5SGO2N76L3?p=preview
I noticed that you were not binding to the items array. I fixed that by using the following markup:
<div ng-repeat="item in items">
<label>
<input type="checkbox" ng-model="item.Selected">{{item.name}}</label>
<br/>
</div>
<label>
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()">Select All</label>
<br/>
After that, I had to change the structure of the items property to become an object for later binding:
$scope.items = [{
name: 'item 1'
}, {
name: 'item 2'
}, {
name: 'item 3'
}, ];
To be able to update all the other checkboxes, I resorted to the following code:
$scope.checkAll = function() {
if ($scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.items, function(item) {
item.Selected = $scope.selectedAll;
});
}
Please, refer to this plunker example for the full working solution.
UPDATE
Use the example here:
https://docs.angularjs.org/api/ng/directive/ngChecked#!
basically the trick is to add to all "slave" check boxes
ng-checked="checkboxModel.value5"
Well, first the explanation:
To select/deselect all the checkboxes, you can simply loop over the elements and setting all the checkbox to true/false.
To select/deselect this checkbox programatically, you can use Array.prototype.every() method, which returns if all checkboxes are selected or not, if all elements are selected that option will be/keep also selected, otherwise, it will be/keep deselected.
To get all the selected items when you close the modal you could use the Array.prototype.filter() method to return only the selected checkboxes.
Here's a snippet working:
(function() {
"use strict";
angular
.module('ui.bootstrap.demo', [
'ngAnimate',
'ui.bootstrap'
])
.controller('ModalDemoCtrl', ModalDemoCtrl)
.controller('ModalInstanceCtrl', ModalInstanceCtrl);
function ModalDemoCtrl($scope, $uibModal, $log) {
$scope.animationsEnabled = true;
$scope.open = function(size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
resolve: {
items: function() {
return $scope.items;
}
}
});
modalInstance.result.then(function(selectedItems) {
$scope.selected = selectedItems;
}, function() {
$log.info('Modal dismissed at: ', new Date());
});
}
$scope.toggleAnimation = function() {
$scope.animationsEnabled = !$scope.animationsEnabled;
}
}
// Please note that $uibModalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
function ModalInstanceCtrl($scope, $uibModalInstance, items) {
$scope.items = [];
function loadData() {
var arr = [];
for (var i = 1; i <= 5; i++) {
arr.push({
"name": "Item " + i
});
}
return arr;
}
$scope.items = loadData();
$scope.check = function() {
$scope.selectedAll = $scope.items.every(function(value) {
return value.Selected;
});
}
$scope.selectAll = function() {
$scope.items.forEach(function(item) {
item.Selected = $scope.selectedAll;
});
}
function getChecked() {
return $scope.items.filter(function(value) {
return value.Selected;
});
}
$scope.ok = function() {
$uibModalInstance.close(getChecked());
}
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
}
}
})();
.main_div {
border: 1px solid red;
width: 30%;
margin: 50px;
padding: 2px;
}
<!DOCTYPE HTML>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular-animate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.0.0/ui-bootstrap-tpls.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-body">
<div class="checkbox" ng-repeat="item in items">
<label>
<input type="checkbox" ng-model="item.Selected" ng-change="check()"> {{item.name}}
</label>
<br/>
</div>
<div class="checkbox">
<label>
<input type="checkbox" ng-model="selectedAll" ng-click="selectAll()"> Select All
</label>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</script>
<button type="button" class="btn btn-default" ng-click="open()">Add data!</button>
</body>
</html>
If you want to see it in plunker, click here.
I hope it helps!!

Can't execute selectall on checkboxes with Angular

I can't seem to figure out how to have another checkbox that selects all and deselects all boxes.
JSFIDDLE
<div ng-controller="tempCtrl">
<input type="checkbox" ng-model="selectAllOptions" ng-click="selectAll()" /> Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
<input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
{{form.selectedTeams}}
</pre>
</div>
var myApp = angular.module('myApp', []);
myApp.controller("tempCtrl", function ($scope) {
$scope.form = {
selectedTeams: {}
};
$scope.parameters = {
myMainOptions: {
teams: ['angels', 'giants', 'orioles', 'bluejays', 'athletics']
}
};
$scope.selectAll = function() {
//This is where I'm stuck
}
});
Here's a working plunkr of a simple select/deselect all checkbox:
plunkr
Controller
$scope.checkboxes = [
{
selected: false
},
{
selected: false
},
{
selected: false
}
];
// Check/uncheck all boxes
$scope.checkAll = function () {
angular.forEach($scope.checkboxes, function (obj) {
obj.selected = $scope.selectAll;
});
};
View
<p>Check all</p>
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<br />
<p>Checkboxes</p>
<div ng-repeat="checkbox in checkboxes track by $index">
<input type="checkbox" ng-model="checkbox.selected" />
<label ng-show="checkbox.selected">Checkbox {{ $index+1 }} selected!</label>
</div>
First, you should make teams an array of objects like this
Controller:
$scope.parameters = {
myMainOptions: {
teams: [{name: 'angels'}, {name: 'giants'}, {name: 'orioles'}, {name:'bluejays'}, {name: 'athletics'}]
}
};
This is a better approach because, now, you can add a selected attribute to each team object.
Then you should set ng-model for each team checkbox to something like team.selected like this:
View:
<li ng-repeat="team in parameters.myMainOptions.teams">
<input ng-model="team.selected" type="checkbox" />
{{team}}
</li>
Now, if you check the angels checkbox, the object will change to {name: 'angels', selected: true}
Then your selectAll function will look like this:
Controller:
$scope.selectAll = function () {
angular.forEach($scope.parameters.myMainOptions.teams, function (team) {
team.selected = $scope.selectAllOptions;
});
};
You could do forEach on $scope.parameters.myMainOptions.teams array and then set $scope.form.selectedTeams value in the loop. Also use ng-change instead of ng-click.
Markup
<input type="checkbox" ng-model="selectAllOptions" ng-change="selectAll()" />Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
<input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
{{form.selectedTeams}}
</pre>
Code
$scope.selectAll = function () {
angular.forEach($scope.parameters.myMainOptions.teams, function (value, index) {
$scope.form.selectedTeams[value] = $scope.selectAllOptions; //setting selectAll variable value
})
}
Working Fiddle

Disable required attribute on one radio button

I have 3 radio buttons in a bootstrap modal and I want only 2 of them to be required in order to submit the form. I created a requiredCheck() function that's using a jQuery implementation so I'd rather not use this. What is the best way to disable the required attribute for one radio button, when using AngularJS?
HTML
<form name="jawn">
<div class="modal-header">
<h3 class="modal-title">Jawn</h3>
</div><!-- /modal-header -->
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
<label for="optionsRadios">
<input type="radio" ng-model="$parent.data.status" name="optionsRadios" ng-value="item.id" required/ ng-click="requiredCheck()"> {{item.name}}
</label>
</li>
</ul>
<h4>Comment</h4>
<textarea ng-class="{error: thing.comment.$dirty && thing.comment.$invalid}" type="text" rows="3" cols="64" ng-model="data.comment" ng-minlength="4" ng-required></textarea>
<span class="error" ng-show="thing.comment.$error.required">required</span>
</div><!-- /modal-body-->
<div class="modal-footer">
<button type="submit" class="btn btn-warning" ng-click="ok()" ng-disabled="thing.$invalid">Part Jawn</button>
<button type="button" ng-click="cancel()" class="btn btn-default">Cancel</button>
</div>
</form>
JavaScript
angular.module('app')
.controller('ModalController', function($scope, $modalInstance, $timeout) {
'use strict';
$scope.item = 0;
$scope.items = [
"Zero": 0,
"Uno": 1,
"Dos": 2
];
$scope.requiredCheck = function () {
var $btnWarning = $('.btn-warning');
var $textarea = $('textarea');
$timeout(function() {
if($scope.data.status === item.Dos) {
$btnWarning.removeAttr('disabled');
$textarea.removeAttr('required');
} else if ($scope.data.status === 3) {
$btnWarning.prop('disabled',true);
$textarea.prop('required', true);
} else if ($scope.data.status === 3) {
$btnWarning.prop('disabled',true);
$textarea.prop('required', true);
}
},100);
};
$scope.ok = function () {
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
$modalInstance.close();
};
});
You should use angualrjs approach. As you have already specified ngRequired set true/false from controller.
From DOCs
ngRequired: Sets required attribute if set to true
HTML
<textarea ng-model="data.comment" ng-required="textRequired"></textarea>
Script
$scope.requiredCheck = function () {
if(condition){
$scope.textRequired = false;
}else{
$scope.textRequired = true;
}
};
Note: I have simplified the answer

Categories