get array values based on checkbox - angularjs

I have a situation where there are 3 check box ("initially checked"). Since it as 3 check box it will use ng-repeat for 3 time and loops the division for there time. Now once i uncheck any of the check box it should display div for 2 time. So far ,
$scope.items = [
{id: 0, title: "apple",selected:true},
{id: 1, title: "orange",selected:true},
{id: 2, title: "grapes",selected:true},
];
On ng-click in each check box i have called a function test("apple").
$scope.test = function(vals) {
$scope.vl=[];
for(var i=0;i<$scope.items.length;i++) {
if($scope.items[i].title == vals) {
console.log("dnt push");
}
else {
$scope.vl.push({
id: $scope.items[i].id,
title: $scope.items[i].title,
selected:true
});
}
}
console.log("vl array");
console.log($scope.vl);
}
Problem I am facing is it works fine for 1st uncheck but not when i do for multiple uncheck. When i check unchecked its not loading div.
In HTML I am using like,
<div ng-repeat="item in vl"> some tags </div>

not quite sure about your question, but hope my answer can give you some hints.
plunker demo
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.items = [{
id: 0,
title: "apple",
selected: true
}, {
id: 1,
title: "orange",
selected: true
}, {
id: 2,
title: "grapes",
selected: true
}];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div ng-repeat="item in items">
<input type="checkbox" ng-model="item.selected">{{item.title}}
</div>
{{items | json}}
</body>
</html>

If and only if you want to put in an array the item who are checked :
http://plnkr.co/edit/DvoPBBvKf3AhYM4qcBhx?p=preview
html
<div ng-repeat="item in items">
<input type="checkbox"
ng-model="item.selected" ng-click="test(item.title)"> {{item.title}}
</div>
controller
$scope.test = function(vals) {
$scope.vl=[];
$scope.vlChecked=[];
for(var i=0;i<$scope.items.length;i++) {
if($scope.items[i].selected) {
$scope.vlChecked.push({
id: $scope.items[i].id,
title: $scope.items[i].title,
selected:true
});
}
}
console.log("vlChecked array");
console.log(JSON.stringify($scope.vlChecked));
}

Related

Ng-value on a select, empty option disapears after selecting a value

I have a ng-repeat iterates through an array and loads my select options, and one of the options is an empty string, but if i click in on the values the empty option disapears, im not sure why
this is my select
<select
class="form-control input-sm"
id="Select7"
name="grossweightmeasurementunitcode"
ng-model="itemForm.grossweightmeasurementunitcode"
ng-readonly="itemForm.produtosempesobrutodefinido"
ng-required="!itemForm.produtosempesobrutodefinido">
<option ng-repeat="unidadepeso in unidadespeso" value="{{unidadepeso.commoncode}}" ng-selected="itemForm.grossweightmeasurementunitcode == unidadepeso.commoncode">{{unidadepeso.sigla}}</option>
</select>
i did a $scope.unidadespeso.push = ' '; to achieve the empty value, any ideas?
Add empty item to array.
Following example might help you.
Please comment if you have any doubts.
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="bootstrap#3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script>
(function() {
angular.module("myapp", []).controller('MainCtrl', ['$scope', function($scope) {
$scope.selectedItem = { name: 'two', id: 27 };
$scope.items = [{name: 'one', id: 30 },{ name: 'two', id: 27 },{ name: 'threex', id: 50 }];
var emptyItem = {name: '', id: '' };
$scope.items.unshift(emptyItem);
}]);
}());
</script>
<style></style>
</head>
<body ng-app="myapp" ng-controller="MainCtrl">
<p>selected item is : {{selectedItem}}</p>
<p> name of selected item is : {{selectedItem.name}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items track by item.id"></select>
</body>
</html>

Insert checked checkbox value at the end

I have a check box with a button.
When I click button checked, checkbox value should be pushed into an array. But it adds at the beginning of an array. I want to add checked checkbox value at the end of the array when clicking the button.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<script src="https://rawgithub.com/angular-ui/ui-sortable/master/src/sortable.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app='test' ng-controller="Test">
<ul>
<li ng-repeat="album in albums">
<input type="checkbox" ng-model="album.selected" value={{album.name}} /> {{album.name}}
</li>
</ul>
<button type='button' ng-click="save()">Save</button><br>
<div ui-sortable="sortableOptionsList[0]" >
{{albumNameArray}}
</div>
<div ui-sortable="sortableOptionsList[0]">
<div class="app" ng-repeat="app in albumNameArray"> {{app.name}}</div>
</div>
</body>
</html>
<script>
angular.module('test', ['ui.sortable'])
.controller('Test', function($scope){
$scope.albums = [{
id: 1,
name: 'test1',
checked : false
},
{
id: 2,
name: 'test2',
checked : false
},
{
id: 3,
name: 'test3',
checked : false
}];
function createOptions (listName) {
console.log('outout');
var _listName = listName;
var options = {
placeholder: "app",
connectWith: ".apps-container",
helper: function(e, item) {
console.log("list " + _listName + ": helper");
return item;
}
};
return options;
}
$scope.sortableOptionsList = [createOptions('A'), createOptions('B')];
$scope.save = function(){
$scope.albumNameArray = [];
angular.forEach($scope.albums, function(album){
console.log(album.selected);
if(album.selected)
{
$scope.albumNameArray.push(album.name);
}
});
}
})
</script>
I have the perfect solution for your query. You just need to make a small change on the logic. Since you want to track the sequence on which the checkboxes are selected, i would suggest you the proper way in AngularJS, using ng-change on the checkbox.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<script src="https://rawgithub.com/angular-ui/ui-sortable/master/src/sortable.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app='test' ng-controller="Test">
<ul>
<li ng-repeat="album in albums">
<input type="checkbox" ng-model="album.selected" value={{album.name}} ng-change='trackOrder(album)' /> {{album.name}}
</li>
</ul>
<button type='button' ng-click="save()">Save</button><br>
<div ui-sortable="sortableOptionsList[0]" >
{{albumNameArray}}
</div>
<div ui-sortable="sortableOptionsList[0]">
<div class="app" ng-repeat="app in albumNameArray"> {{app.name}}</div>
</div>
</body>
</html>
<script>
angular.module('test', ['ui.sortable'])
.controller('Test', function($scope){
$scope.albumArray = [];
$scope.albums = [{
id: 1,
name: 'test1',
checked : false
},
{
id: 2,
name: 'test2',
checked : false
},
{
id: 3,
name: 'test3',
checked : false
}];
function createOptions (listName) {
console.log('outout');
var _listName = listName;
var options = {
placeholder: "app",
connectWith: ".apps-container",
helper: function(e, item) {
console.log("list " + _listName + ": helper");
return item;
}
};
return options;
}
$scope.sortableOptionsList = [createOptions('A'), createOptions('B')];
$scope.trackOrder = function(album){
//add album in the array
if(album.selected){
$scope.albumArray.push(album.name);
}else{
//remove album fron the array
var index = $scope.albumArray.indexOf(album.name);
$scope.albumArray.splice(index,1);
}
}
$scope.save = function(){
//if you want the value on albumNameArray on click on save use this else you can
//use the $scope.albumArray directly
$scope.albumNameArray = angular.copy($scope.albumArray);
}
})
</script>
Here is the plunkr link PLUNKR
use unshift.
$scope.albumNameArray.unshift(album.name);

Angular closest child on SELECT

Angular 1.4.x
In a ng-repeat I have a SELECT control and under it a DIV of details. When the SELECT is changed I wish to add a class to the DIV.
BEGIN ng-repeat
<select ng-change="???add a class XYZ to .details ???">...</select>
<div class="details">...</div>
END
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.selection = [];
$scope.isHighlighted = [];
$scope.items = [{
id: 1,
label: 'Label 1',
}, {
id: 2,
label: 'Label 2',
}];
$scope.selectionChanged = function(idx) {
$scope.isHighlighted[idx] = true;
}
});
.highlight {
color: red;
}
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.js" data-semver="1.5.10"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="item in items">
<select ng-options="item as item.label for item in items track by item.id" ng-model="selection[$index]" ng-change="selectionChanged($index)"></select>
<div ng-class="{highlight:isHighlighted[$index]}">Some Div Content</div>
</div>
</body>
</html>

angular datatables change number of columns

I'm using angular-datatables ( http://l-lin.github.io/angular-datatables/#/welcome ).
I put up this Plunker: http://plnkr.co/edit/ZRvQt7KBZam22Yt5S4QC?p=preview .
I'm trying to dynamically change the number of columns in my datatable, based on data pulled from the server. Is there a way to do this ? I'm using the control "the Angular way':
<table datatable="ng"></table>
Thank you in advance for taking time to look at this.
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />'); </script>
<link rel="stylesheet" href="style.css" />
</head>
<body ng-controller="MainCtrl as mCtrl">
<table id="dtFeeDetails" datatable="ng" dt-options="mCtrl.dtOptionsForFeeDetails" dt-column-defs="mCtrl.dtColumnDefs" dt-instance="mCtrl.dtInstance">
<tbody>
<tr dt-rows ng-repeat="f in feeData">
<td ng-repeat="c in colHeadings">{{f[c.Value]}}</td>
</tr>
</tbody>
</table>
<p>
<button type="button" ng-click="changeColumnDefs()">Change column defs</button>
</p>
<script data-require="jquery#1.10.1" data-semver="1.10.1" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="//cdn.datatables.net/1.10.1/js/jquery.dataTables.js"></script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script type="text/javascript" src="https://rawgithub.com/l-lin/angular-datatables/dev/dist/angular-datatables.min.js"></script>
<script src="app.js"></script>
app.js
var app = angular.module('plunker', ['datatables']);
app.controller('MainCtrl', function($scope, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder) {
var vm = this;
$scope.feeData = [{ val1: 'data1'}, { val1: 'data2'}];
$scope.colHeadings = [{ Value: 'val1' }];
vm.dtInstance = {};
vm.dtColumnDefs = [
DTColumnDefBuilder.newColumnDef(0).withTitle($scope.colHeadings[0].Value)
];
vm.dtOptionsForFeeDetails = DTOptionsBuilder.newOptions();
var dtFeeDetailsID = "dtFeeDetails";
$scope.changeColumnDefs = function() {
//$('#' + dtFeeDetailsID).DataTable().destroy();
//$('#' + dtFeeDetailsID).dataTable();
// this won't work, because we're changing the number of columns
$scope.colHeadings = [{ Value: 'val1' }, { Value: 'val2' }];
$scope.feeData = [{ val1: 'data3', val2: 'data5'}, { val1: 'data4', val2: 'data6'}];
vm.dtColumnDefs = [];
vm.dtColumnDefs = [
DTColumnDefBuilder.newColumnDef(0).withTitle($scope.colHeadings[0].Value),
DTColumnDefBuilder.newColumnDef(0).withTitle($scope.colHeadings[1].Value)
];
// this will work, because we're keeping the same number of columns
//$scope.colHeadings = [{ Value: 'val2' }];
//$scope.feeData = [{ val2: 'data3'}, { val2: 'data4'}];
//vm.dtColumnDefs = [];
//vm.dtColumnDefs = [
// DTColumnDefBuilder.newColumnDef(0).withTitle($scope.colHeadings[0].Value),
// ];
};
});

How to filter array if filter is in angular directive?

I try to create general directive for filtering array in angular.
<body ng-controller="MainCtrl">
controller: <input type="text" ng-model="query.name" /> - work<br>
directive: <span filter by="name"></span> - not work
<ul>
<li ng-repeat="item in list | filter:query">{{item.name}}</li>
</ul>
</body>
controller and directive are:
app.controller('MainCtrl', function($scope) {
$scope.list = [
{id: 1, name:'aaa'},
{id: 2, name:'bbb'},
{id: 3, name:'ccc'}
];
});
app.directive('filter', function () {
return {
scope: {
by: '#'
},
link: function postLink(scope, element, attrs) {
element.append(
'<input type="text" ng-model="query.' + attrs.by + '">');
}
}
});
Filter in controller works but filter in directive doesn't. I don't know how to fix it.
Solution is fixed in plunker: http://plnkr.co/edit/WLGd6RPQEwMFRBvWslpt?p=preview
Since you have isolated the scopes you have to use eiter $parent or you have to set up two way binding using '=' i have update your example with two way binding
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
controller: <input type="text" ng-model="query.name" /> - work<br>
directive: <span filter by="query"></span> - not work
<ul>
<li ng-repeat="item in list | filter:query">{{item.name}}</li>
</ul>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope) {
$scope.list = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
alert("123");
$scope.query = { name: "" }
});
app.directive('filter', function () {
return {
scope: {
by: '='
},
replace: true,
template:'<input ng-model="by.name"></input>'
}
});
</script>
</body>
</html>

Resources