Make Angular checkbox unselect - javascript

I have requirement where from array i have to create list of checkbox using classes.now again one reset button will be there after clicking on that all selection will be reseted , how to do that thanks
$scope.classList=['Class1','Class2','Class3','Class4'];
$scope.selectedClasses={};
$scope.selectedClasses.usall=false;
$scope.selectedClasses.sall=false;
$scope.selectedClasses.classListchecked=false;
$scope.getSubscribedClassList = function(classNam) {
if(classNam==="All"){
$scope.selectedClasses.usall=false;
$scope.selectedClasses.classListchecked=false;
}
else{
$scope.selectedClasses.usall=false;
$scope.selectedClasses.sall=false;
$scope.selectedClasses.classListchecked.push(classNam)
}
}
Below is my fiddle link
http://jsfiddle.net/alokranjan39/49cc14yk/38/

I have made few changes in your fiddle (forked it here - http://jsfiddle.net/9Lv8gdr3/1/)
HTML:
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="masterSelect" ng-click="getSubscribedClassList('All')"> UnSelectAll
<li ng-repeat="class in classList">
<span>
<input type="checkbox" ng-model="class.isSelected" ng-disabled="class.students.length==0">
{{class.name}} </span>
</li>
</div>
JavaScript:
function MyCtrl($scope) {
$scope.classList = [{
isSelected: false,
name: 'Class1'
}, {
isSelected: false,
name: 'Class2'
}, {
isSelected: false,
name: 'Class3'
}, {
isSelected: false,
name: 'Class4'
}];
$scope.getSubscribedClassList = function(classNam) {
if (classNam === "All") {
angular.forEach($scope.classList, function(value, index) {
value.isSelected = $scope.masterSelect;
});
} else {
//you dont ideally need this. get the items with isSelected === true from $scope.classList to get the checked items
}
};
}
To get the list of selected item, just loop through the $scope.classList and get the items for which isSelected === true

Updated your fiddle - http://jsfiddle.net/49cc14yk/43/
HTML :
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="selectedClasses" ng-click="getSubscribedClassList()">
UnSelectAll
<li ng-repeat="class in classList">
<span>
<input type="checkbox" ng-model="class.value">
{{class.label}}
</span>
</li>
</div>
JS :
function MyCtrl($scope) {
$scope.classList=[{
label: 'Class1', value: false
}, {
label: 'Class2', value: false
}, {
label: 'Class3', value: false
}, {
label: 'Class4', value: false
}];
$scope.getSubscribedClassList = function() {
$scope.classList.forEach(function(obj) {
obj.value = $scope.selectedClasses;
});
}
}

Have updated fiddle for array also - http://jsfiddle.net/49cc14yk/45/
HTML :
<div ng-controller="MyCtrl">
<input type="checkbox" ng-model="selectAll" ng-click="getSubscribedClassList('ALL')">
UnSelectAll
<li ng-repeat="class in classList">
<span>
<input type="checkbox" name="selectedClasses[]" value="{{class}}"
ng-checked="selectedClassList.indexOf(class) > -1" ng-click="getSubscribedClassList(class)">
{{class}}
</span>
</li>
</div>
JS :
function MyCtrl($scope) {
$scope.classList = ['Class1','Class2','Class3','Class4'];
// Initialise below array as per your requirement, maybe blank
$scope.selectedClassList = ['Class1','Class2'];
$scope.getSubscribedClassList = function(value) {
if(value == 'ALL') {
$scope.selectedClassList = [];
if($scope.selectAll) {
$scope.selectedClassList = Object.create($scope.classList);
}
} else {
var idx = $scope.selectedClassList.indexOf(value);
if (idx > -1) {
$scope.selectedClassList.splice(idx, 1);
} else {
$scope.selectedClassList.push(value);
}
}
};
}
Using as object is more appropriate so keeping that answer too

Related

create observables dynamically and show it in html ,knockout?

HTML :-
<div class="row" style="margin-left: 10px;" data-bind="foreach: {data: data, as: 'data1'}">
<span style="color: red; display: none;" data-bind="attr:{'id':data1.mandatory!=0?'id'+data1.dynamicid:''},text: 'You have selected ' +app.vm.observables.totalSelected()+ ' Observation areas. Please restrict to only 2.'"></span>
</div>
here the observable is same for every div element id so value is showing same how to do it dynamically?
JAVASCRIPT :-
`$('#id'+dynamicid+' input:checkbox.paramValues:checked').each(function(e){
DataImprove++;
});`
if(DataImprove>2){
vm.observables.totalSelected(DataImprove);
}
Need to create observables dynamically based on the div element ids and show it in the frontend HTML.
I'm not entirely sure I understand what you are trying to do, but hopefully this helps
I think it would make sense to move some of the functionality out out the view and into a viewModel
var externalData = [{
mandatory: false,
dynamicid: 1,
}, {
mandatory: false,
dynamicid: 2,
}, {
mandatory: 1,
dynamicid: 3,
}, {
mandatory: false,
dynamicid: 4,
}];
function ViewModel() {
var self = this;
self.data = ko.observableArray([]);
self.totalSelected = ko.pureComputed(function() {
return self.data().filter(function(i) {
return i.selected() === true;
}).length;
});
self.selectedText = ko.pureComputed(function(){
return 'You have selected ' + self.totalSelected() + ' Observation areas.';
});
var mappedData = externalData.map(function(item) {
return {
mandatory: item.mandatory,
dynamicid: item.dynamicid,
selected: ko.observable(false),
mandatoryStatus: item.mandatory == true ? 'mandatory' : ''
};
});
self.data(mappedData);
}
var vm = new ViewModel();
ko.applyBindings(vm);
.mandatory {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: selectedText"></span>
<ul data-bind="foreach: {data: data, as: 'data1'}">
<li data-bind="class: mandatoryStatus">
<label data-bind="text: dynamicid"></label>
<input type="checkbox" data-bind="checked: selected" />
</li>
</ul>

Vue component watch

all how i can watch changes in my component in data?
I need watch when user choose car brand to take from server models for that brand
this is my code
Templete
<template>
<div class="category-info">
<div v-for="input in inputs.text">
<label >{{ input.placeholder}}</label>
<input type="text" id="location" :name="input.name" v-model="input.value" #click="console">
</div>
<div class="select" v-for="select in inputs.select">
<label >{{ select.placeholder }}</label>
<my-select :data="select" v-model="select.value"></my-select>
</div>
<button #click="console">click</button>
</div>
Script
<script>
export default {
name: "profile-add-inputs",
props: ['category'],
data() {
return {
inputs: {
text : {},
select: {}
},
}
},
methods: {
getCategories(){
axios.get('/profile/inputs', {
params: {
category: JSON.stringify(this.category.href)
}
})
.then((response) => {
this.inputs.text = response.data.text;
this.inputs.select = response.data.select;
for(let key in this.inputs.text){
this.inputs.text[key].value = '';
}
for(let key in this.inputs.select){
this.inputs.select[key].value = '';
if(this.category.href.sub == 'car' && this.inputs.select[key].name == 'brand'){
console.log('CAR BREND');
this.$watch.inputs.select[key].value = function () {
console.log(this.inputs.select[key].value);
}
}
}
},this)
.catch(function (error) {
console.log(error);
});
},
console(){
console.log(this.inputs.select);
}
},
watch: {
category : function () {
this.getCategories();
console.log('categoty');
},
inputs : {
handler() {
console.log('watch inputs');
}
}
}
}
So, i tried to use watch and $watch but its not working, plz give me a reason why that not work, or maybe some another way to resolve this problem
this.$watch can i create dynamiclly watchers with this stement?
The correct syntax is
watch : {
inputs : function(val, oldVal){
//val : New value
//oldVal : Previous value.
}
}

AngularJS custom filter with checkbox and radio button

My application has to dynamically list file items using a Radio button, Checkbox and AngularJS custom filter (code given below).
I have tried few options, but could not get the working code.
I have created the fiddle link and find the same below:
https://jsfiddle.net/38m1510d/6/
Could you please help me to complete the below code to list the file items dynamically ?
Thank you.
<div ng-app="myApp" ng-controller="myCtrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="myFilter(?, ?)"> by X
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="myFilter(?, ?)"> by All
</label> <br/><br/>
<label>
<input type='checkbox' ng-model='Type1Files' ng-change='myFilter(?, ?)'>Type1 files
<input type='checkbox' ng-model='Type2Files' ng-change='myFilter(?, ?)'>Type2 files
</label>
<br/><br/>
<label ng-repeat="file in displayFiles | filter: myFilter(createdBy, fileType)">
{{ file.name }}
</label>
</div>
</body>
<script>
var app = angular.module("myApp",[]);
app.controller('myCtrl', function ($scope) {
$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];
$scope.displayFiles = [];
$scope.myFilter = function() {
return new function(createdBy, fileType) {
var displayFilesTemp = [];
for(i=0;i<$scope.files.length;i++) {
if($scope.files[i].type ==fileType && $scope.files[i].createdBy == createdBy && !checkArrayContainsObject(displayFilesTemp, displayFiles[i])) {
displayFilesTemp.push(displayFiles[i]);
}
}
return displayFilesTemp;
};
};
});
function checkArrayContainsObject(a, obj) {
for (var i = 0; i < a.length; i++) {
if (JSON.stringify(a[i]) == JSON.stringify(obj)) {
return true;
}
}
return false;
}
</script>
Here's a working fiddle - http://jsfiddle.net/1gfaocLb/
Radio is a unique value, so it's easy to filter by.
Selected types are array of values so it's needs a little more attention.
myApp.filter('typesFilter', function() {
return function(files, types) {
return files.filter(function(file) {
if(types.indexOf(file.type) > -1){
return true;
}else{
return false;
}
});
};
});
According the shared code / fiddle, I've simplified the code for a possible solution. The file filtering logic is not foreseen since it was not clear what needed to be done exact.
<body ng-app="myapp">
<div ng-controller="myctrl">
<label>
<input type="radio" ng-model="inputCreatedBy" value="byX"
ng-click="filterFiles()"> by X
<input type="radio" ng-model="inputCreatedBy" value="byAll"
ng-click="filterFiles()"> by All
</label> <br/><br/>
<label>
<input type='checkbox' ng-model='Type1Files' ng-change='filterFiles()'>Type1 files
<input type='checkbox' ng-model='Type2Files' ng-change='filterFiles()'>Type2 files
</label>
<br/><br/>
<label ng-repeat="file in filteredFiles">
{{ file.name }} <br/>
</label>
</div>
</body>
var app = angular.module("myapp",[])
app.controller('myctrl', function ($scope) {
$scope.files = [
{ name: 'file1', type:'Type1', createdBy: 'X' },
{ name: 'file2', type:'Type2', createdBy: 'X' },
{ name: 'file3', type:'Type2', createdBy: 'Y' },
{ name: 'file4', type:'Type1', createdBy: 'Y' }
];
$scope.filterFiles = function(){
// init dict
var files = [];
// loop & check files
angular.forEach($scope.files, function(value, key) {
// do file check and push to files.push when matching with criteria
files.push(value);
});
// set scope files
$scope.filteredFiles = files;
}
// init filter on ctrl load
$scope.filterFiles();
});
First, you don't have to use any directive as ng-if/ng-click to achieve what you want. Just changing how the values are binding into the radio button and checkbox can do the trick. Also you just need to do a custom filter to handle the checkbox selections, since radio button is unique. Take a look on my solution:
angular.module("myApp", [])
.controller('myCtrl', function($scope) {
$scope.files = [
{
"name":"file1",
"type":"Type1",
"createdBy":"X"
},
{
"name":"file2",
"type":"Type2",
"createdBy":"X"
},
{
"name":"file3",
"type":"Type2",
"createdBy":"Y"
},
{
"name":"file4",
"type":"Type1",
"createdBy":"Y"
}
];
})
.filter('typesFilter', function() {
return function(files, types) {
if (!types || (!types['Type1'] && !types['Type2'])) {
return files;
}
return files.filter(function(file) {
return types['Type1'] && file.type == 'Type1' || types['Type2'] && file.type == 'Type2';
});
};
});
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="myCtrl">
<form action="" name="form">
Created by:
<input type="radio" id="radio1" ng-model="criteria.createdBy" value="X">
<label for="radio1">by X</label>
<input type="radio" id="radio2" ng-model="criteria.createdBy" value="">
<label for="radio2">by All</label>
<br/>
<br/>
Type:
<input type="checkbox" id="check1" ng-model="criteria.type['Type1']">
<label for="check1">Type1 files</label>
<input type="checkbox" id="check2" ng-model="criteria.type['Type2']">
<label for="check2">Type2 files</label>
</form>
<pre ng-bind="criteria | json"></pre>
<div ng-repeat="file in files | filter: { createdBy: criteria.createdBy } | typesFilter: criteria.type" ng-bind="file.name"></div>
</body>
</html>

How do I detect if an object has been added using angular.forEach AngularJS

I am trying to add objects to $scope.orderitems and if the object is already in the $scope.orderitems I want to change the quantity property of the object using angular.forEach instead of adding another object. Whenever I call the additem function I get an error that orderitems is not defined.
Here is my code
HTML
<input type="text" ng-model="item.name">
<button type="button" ng-click="additem(item)">
<ul>
<li ng-repeat="orderitem in orderitems">
<p>{{ orderitem.name }} | {{ orderitem.qty }}</p>
</li>
</ul>
JS
app.controller('OrderCtrl', function($scope) {
$scope.orderitems = [];
$scope.additem = function(data) {
angular.forEach(orderitems, function(orderitem) {
if (orderitem.id === data.id) {
orderitem.qty = orderitem.qty++;
} else {
data.qty = 1;
$scope.orderitems.push(data);
}
});
};
});
Here's a working fiddle: http://jsfiddle.net/rodhartzell/hbN4G/
HTML
<body ng-app="app">
<div ng-controller="OrderCtrl">
<input type="text" ng-model="item.name">
<button type="button" ng-click="additem()">add</button>
<ul>
<li ng-repeat="orderitem in orderitems">
<p>{{ orderitem.name }} | {{ orderitem.qty }}</p>
</li>
</ul>
</div>
CONTROLLER
var app = angular.module('app', []);
app.controller('OrderCtrl', function($scope) {
$scope.orderitems = [{name: 'foo', id:1, qty:1}];
$scope.additem = function() {
var exists = false;
var data = {
id : $scope.orderitems.length + 1,
name: $scope.item.name,
qty: 1
}
angular.forEach($scope.orderitems, function (item) {
if (item.name == data.name) {
exists = true;
item.qty++;
return false;
}
});
if(!exists){
$scope.orderitems.push(data);
}
};
});
$scope.orderitems = [];
$scope.additem = function(data) {
var item = null
angular.forEach(orderitems, function(orderItem) {
if (orderItem.id === data.id) {
item = orderItem
return false;
}
});
if (item == null) {
item = {
id: data.id, qty : 0
}
$scope.orderitems.push(item)
}
item.qty++
};

Assign ng-model to checkbox if some value == anothervalue

I have a User object in Angular controller. I also have an array of Account objects with respective ID for each.
In User I have a field "default_account" where I want to put ID of a default account. So, user can have a lot of accounts but only one of them can be default. When I go to Account options, I have a checkbox there which is responsible for setting/unsetting the account as default.
Now I want to set checkbox on/off depending on its being default for the user. And I also need to respectively change default_account field inside User object on checkbox change. It puzzles me quite much how I can do it.
Any advice is appreciated!
Very approximate (didn't text that):
html:
<div ng-repeat="account in accounts">
<input type="checkbox" ng-checked="account == user.default_acount"
ng-click="SelectAssDefault(account )" />
</div>
js:
function MyCtrl($scope) {
$scope.user = { name: 'user', default_acount: null};
$scope.accounts = [{ }, { }, ...];
$scope.SelectAssDefault = function (account) {
$scope.user.default_acount = account;
};
}
EDIT: a working example: http://jsfiddle.net/ev62U/120/
If you want to set a checkbox to true based on a variable, you can set ng-checked="variable" within the input tag.
If the variable is true the box will be checked. If it's false it won't. Alternatively, an expression will also work e.g. ng-checked="1===1" will evaluate to true.
If you want to alter something else based on user clicking on the checkbox, set ng-click="someCtrlFunction()" within the input tag. This will call a function in your controller. You can look up the value of the checkbox from your controller if you've bound to it.
Here's a fiddle: http://jsfiddle.net/E8LBV/10/ and here's the code:
HTML
<div ng-app="App">
<div ng-controller="AppCtrl">
<ul>
<li ng-repeat="user in users">{{user.name}}
<ul>
<li ng-repeat="account in user.accounts">
<input type="checkbox" ng-model="checked" ng-checked="account == user.default" ng-click="changeDefault(user.id,account,checked)">{{account}}</input>
</li>
<ul/>
</li>
</ul>
</div>
</div>
JS
var app = angular.module('App', []);
app.service('Users', function () {
var Users = {};
Users.data = [{
'id': 1,
'name': 'jon',
'default': null
}, {
'id': 2,
'name': 'pete',
'default': null
}];
return Users;
});
app.service('Accounts', function () {
var Accounts = {};
Accounts.data = [{
'user': 1,
'ac': 123456
}, {
'user': 2,
'ac': 456832
}, {
'user': 2,
'ac': 345632
}, {
'user': 1,
'ac': 677456
}];
return Accounts;
});
app.controller('AppCtrl', function ($scope, Users, Accounts) {
$scope.users = Users.data;
//attach accounts to user
for (i = 0; i < $scope.users.length; i++) {
$scope.users[i].accounts = [];
for (ii = 0; ii < Accounts.data.length; ii++) {
if (Accounts.data[ii].user == $scope.users[i].id) {
$scope.users[i].accounts.push(Accounts.data[ii].ac);
}
}
}
//function to change the default account for the user
$scope.changeDefault = function (id, account, checked) {
if (!checked) {
return;
}
for (i = 0; i < $scope.users.length; i++) {
if ($scope.users[i].id == id) {
$scope.users[i].
default = account;
}
}
}
});
Here is my solution that perfectly worked for me!
<tbody ng-repeat="account in accounts">
<tr>
<td ><a ng-click="getloandetails(account.idAccount)">{{account.accountName}}</a></td>
<td>$ {{account.currentBalance}}</td>
</tr>
</tbody>
and in Angular side just do this:
$scope.getloandetails = function(accountId) {
alert('Gettring details for the accountId: ' + accountId);
};

Categories

Resources