how can we get the array id of selected checkbox in angularjs? - angularjs

I am trying to get the array id of selected checkbox but unable to get the array. I need the array in format of ["302740", "42006", "331497"]
here it is my app.js
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
$scope.brandlist = [];
$scope.get = function (val) {
console.log(val);
var idx = $scope.brandlist.indexOf(val);
if (idx > -1)
$scope.brandlist.splice(idx, 1);
else
$scope.brandlist.push(val);
console.log($scope.brandlist);
// should come like selected array ["302740", "42006", "331497"]
}
}
and here it is the html
<div ng-controller="Ctrl">
<span ng-repeat="(key,val) in categories">
<label class="checkbox" for="{{key.tid}}">
<input type="checkbox" ng-change="get(val.tid)" ng-model="brandlist[val.tid]" ng-checked="brandlist.indexOf(val.tid) > -1" name="group" id="{{val.tid}}" />
{{val.name}}
</label>
</span>
</div>
plunker

Consider trying this
$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
$scope.selecetedCategories = function toggleSelection(category){
var idx = $scope.selectedCategories.indexOf(category);
if(idx > -1){
$scope.selecetedCategories.splice(idx,1);
}
else{
$scope.selecetedCategories.push(category);
}
};
You can print the selected categories like this
console.log($scope.selecetedCategorie);
And your html:
<input type="checkbox" name="selectedCategories"
value="{{category}}" ng-checked="selectedCategories.indexOf(category) >
-1" ng-click="toggleSelection(category)"/>

If you're not worried about manipulating the source array, you can use that to maintain the state.
HTML
<div ng-controller="Ctrl">
<span ng-repeat="(key,val) in categories">
<label class="checkbox" for="{{key.tid}}">
<input type="checkbox" ng-model="val.checked" name="group" id="{{val.tid}}" />
{{val.name}}
</label>
</span>
</div>
JS:
$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
// get the selected categories
var selectedCategories = $scope.categories.filter(function(itm) {
return itm.checked;
});

Related

Angularjs ng-change and ng-repeat not properly working

In ng-change the selected value is not setting up in the ngchange function.
First time when I select a value its setting up as null, and again I try to select an another value, its setting the value of the previous selected value.
var ngInitParams = JsonConvert.SerializeObject(Model);
var firstVarId= Model.Variants.First().ProductId;
var firstVarName= Model.Variants.First().Name;
<section id="#inPageNavigationID" ng-controller="prodSpecsCtrl as main"
ng-init="main.init('#firstVarId', '#firstVarName')">
<div class="container" ng-init="main.loadSelect('#ngInitParams')">
<div>
<div class="row">
<div class="col-sm-6 fieldset">
<div class="form__item ">
<div>
<select class="-dropdown--two-columns" name="productvariants" id="sel1" data-placeholder="#selectOptionVal" ng-model="variant.ProductId"
ng-change="main.load('{{variant.ProductId}}','{{(main.JsonVariants.Variants | filter: {ProductId:variant.ProductId})[0].Name}}')">
<option value="" disabled>Select Model</option>
<option ng-repeat="variant in main.JsonVariants.Variants" value="{{variant.ProductId}}" selected="#firstVariantId" data-option-header="{{variant.CatalogCode}}">{{variant.Name}}</option>
</select>
<span class="fa fa-angle-down"></span>
</div>
</div>
</div>
</div>
</div>
<section>
this.init = function (varId, varName) {
this.load(varId, varName);
}
this.loadSelect = function (strjson) {
self.JsonVariants = JSON.parse(strjson);
}
Here is an example of an ng-change within a select.
https://plnkr.co/edit/ZhJbVfPRCLoeFwYoi3Mp?p=preview
<body ng-controller="MainCtrl">
<select ng-model="item" ng-change="changed(item)" ng-options="item.Name for item in items"></select>
<p>ID:{{selected.ID}} Name: {{selected.Name}}</p>
<p>You Selected: {{selected}}</p>
</body>
And Controller:
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.selected = {};
$scope.changed = function(item) {
$scope.selected = item;
}
function setupItems() {
for (var i = 0; i < 10; i++) {
var item = {ID: i, Name: "Item " + i}
$scope.items.push(item);
}
}
setupItems();
});

Angularjs: Populating the drop-down as per user input

I am new to Angularjs. I am trying to do is like this. I have an input field where user inputs a number. Then a dropdown is generated where number of options should be equal to the number entered by the user. Here is my code:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.addqty = function() {
var i;
for (i = 0; i < $scope.quantity; i++) {
$scope.choices = i;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Enter quantity: <input type="text" ng-model="qauntity" />
<button ng-click="addqty()">Add</button>
<fieldset data-ng-repeat="choice in choices">
<select>{{choices}}</select>
</fieldset>
</div>
Try something like this:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.choices = [];
$scope.quantity = 0;
$scope.addqty = function() {
$scope.choices = [];
for (i = 0; i < $scope.quantity; i++) {
$scope.choices.push(i)
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Enter quantity: <input type="number" ng-model="quantity" />
<button ng-click="addqty()">Add</button>
<div>
<select>
<option ng-repeat="choice in choices">
{{choice}}
</option>
</select>
</div>
</div>
You have an empty array, then when you click the button an amount of items equal to the quantity that was input is pushed into the array, which in turn is used to populate the select. I think type="number" on the input is more appropriate in this instance, to make sure the user doesn't use text instead of a number.
$scope.choices = []; resets the array to empty before starting to populate it again, in case someone clicks the button multiple times.
If you want to spice things up a little and make the whole thing a little neater you can add <div ng-show="choices.length > 0"> around the select-tag. This will ensure that the dropdown is only rendered when there's atleast one item in the array.
All that's left to do then is make sure you can actually continue working with the selected value:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.choices = [];
$scope.quantity = 0;
$scope.selected;
$scope.addqty = function() {
$scope.choices = [];
for (i = 0; i < $scope.quantity; i++) {
$scope.choices.push(i)
$scope.selected = $scope.choices[0];
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Enter quantity: <input type="number" ng-model="quantity" />
<button ng-click="addqty()">Add</button>
<div ng-show="choices.length > 0">
<select ng-model="selected">
<option ng-repeat="choice in choices">
{{choice}}
</option>
</select>
</div>
<div ng-show="choices.length > 0">
<label>Selected value: {{selected}}</label>
</div>
</div>
You don't have to write any javascript function to do this. You can make use of array.constructor method and pass the corresponding input number value to implement the functionality.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl"> Enter quantity:
<input type="number" ng-model="quantity" />
<button ng-click="val=quantity">Add</button>
<div ng-if="val!=undefined">
<select>
<option value="{{$index+1}}" ng-repeat="x in [].constructor(val) track by $index"> {{$index+1}} </option>
</select>
</div>
</div>
angular.module('app', []).controller('ctrl', function($scope){
$scope.show = function(){
$scope.array = [];
for(var i = 0; i < $scope.quantity; i++)
$scope.array.push(i + 1);
$scope.selected = $scope.array[0];
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='ctrl'>
<input type='number' ng-model='quantity' />
<input type='button' ng-click='show()' value='Create' />
</br>
<select ng-model='selected' ng-options="item for item in array">
</select>
</div>
You could create an array of objects in the scope and in your addqty function you can push an object to that array which includes the value and the text you want to the user to see.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.choises = [];
$scope.addqty = function() {
var i;
for (i = 0; i < $scope.quantity; i++) {
$scope.choises.push({value:i,text:'text'});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Enter quantity: <input type="text" ng-model="quantity" />
<button ng-click="addqty()">Add</button>
<div ng-show="choises.length > 0">
<select>
<option
value="{{choise.value}}"
ng-repeat="choise in choises">
{{choise.text}}
</option>
</select>
</div>
</div>
Just made more better by hiding the New dropdown until no value is assigned:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.choices = [];
$scope.quantity = 0;
$scope.addqty = function() {
$scope.choices = [];
for (i = 0; i < $scope.quantity; i++) {
$scope.choices.push(i)
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Enter quantity: <input type="number" ng-model="quantity" />
<button ng-click="addqty()">Add</button>
<div>
<select ng-show="choices.length">
<option ng-repeat="choice in choices">
{{choice}}
</option>
</select>
</div>
</div>

Get the value of dynamic check boxes in angular js when submitting the form

In my HTML form there are 5 check boxes. How can I check which check boxes are checked or not at the time of the form submission?
I am using this little piece of code. Feel free to take it.
In your controller:
$scope.sentinel = [];
$scope.toggleSelection = function(value) {
// Bit trick, equivalent to "contains"
if (~$scope.sentinel.indexOf(value)) {
var idx = $scope.sentinel.indexOf(value);
$scope.sentinel.splice(idx, 1);
return;
}
$scope.sentinel.push(value);
};
Then in your HTML:
<span ng-repeat="key in $scope.yourarray">
<md-checkbox style="margin-left:30px;" aria-label="Select item"
ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox>
<br/>
</span>
This allows you to have an array of any size and using the sentinel array to register already checked values. If you check again a box, the toogleSelection will prevent you from adding again a value.
You can use the Checklist-model of Angular.js. It is very useful:
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkAll = function() {
$scope.user.roles = angular.copy($scope.roles);
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
};
$scope.showCheckedOnes = function() {
var checkedBoxes = "";
for (var i = 0; i < $scope.user.roles.length; i++) {
checkedBoxes += $scope.user.roles[i] + " ";
}
alert(checkedBoxes);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl1">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
</label>
<div>
<div>
<button ng-click="checkAll()" style="margin-right: 10px">Check all</button>
<button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button>
<button ng-click="checkFirst()" style="margin-right: 10px">Check first</button>
<button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>
You can define the array value and map to html.
$scope.checkbox = [];
HTML
<input ng-model="checkbox[0] type="checkbox" />
<input ng-model="checkbox[1] type="checkbox" />
<input ng-model="checkbox[2] type="checkbox" />
<input ng-model="checkbox[4] type="checkbox" />
Or you can define checkbox as object and change checkbox[index] to checkbox[name].

All checkboxes get checked when one is checked (should be just the one checked) - inputs generated with angular js

I am making app with angular js. It goes like this.
User creates groups and adds group names
User creates 'websites' and for each website he can check groups that are created in previous step
Problem is that all groups checkboxes get checked when he checks just one.
Here is the code that generates the checkboxes:
<p>Groups:
<label ng-repeat='group in groups'>
<input type="checkbox" ng-model="newSite.groups" name="group-check" value="{{group.id}}"/>
{{group.name}}</label></p>
Here is the code that is outputed:
<label ng-repeat="group in groups" class="ng-scope ng-binding">
<input type="checkbox" ng-model="newSite.groups" name="group-check" value="0" class="ng-valid ng-dirty">
first group</label>
<label ng-repeat="group in groups" class="ng-scope ng-binding">
<input type="checkbox" ng-model="newSite.groups" name="group-check" value="1" class="ng-pristine ng-valid">
second group</label>
Thanks!
edit: here is the plunker link http://beta.plnkr.co/edit/OVBoTDY2YmXgSy8TAbIW
This (plunker) is how I would do it. The idea is to create a model to keep track of checked groups.
JS
app.controller("WebsitesCtrl", function($scope) {
$scope.newSite = {};
$scope.newGroup = {};
$scope.checkedGroupIds = {};
$scope.sites = [];
var groupMap = {};
$scope.groups = [];
var siteIdSeq = 0;
function createSite(newSite, groups) {
$scope.sites.push(newSite);
newSite.id = siteIdSeq;
newSite.groups = groups;
siteIdSeq++;
return newSite;
}
var groupIdSeq = 0;
function createGroup(newGroup) {
$scope.groups.push(newGroup);
newGroup.id = groupIdSeq;
groupMap[newGroup.id] = newGroup;
groupIdSeq++;
return newGroup;
}
$scope.submitSite = function() {
var groups = [];
angular.forEach($scope.checkedGroupIds, function(checked, id) {
if(checked) {
groups.push(groupMap[id]);
}
});
createSite($scope.newSite, groups);
$scope.newSite = {};
$scope.checkedGroupIds = {};
};
$scope.submitGroup = function() {
createGroup($scope.newGroup);
$scope.newGroup = {};
};
//test data
$scope.newSite.url = 'http://www.my-site.com';
var all = createGroup({name:'All'});
var home = createGroup({name:'Home'});
var fav = createGroup({name:'Fav'});
createSite({url:'http://www.stackoverflow.com'}, [all, fav]);
createSite({url:'http://www.google.com'}, [fav]);
createSite({url:'http://www.plnkr.co'}, [home]);
});
HTML
<div id="website-form">
Sites:
<ul>
<li ng-repeat="site in sites">{{site}}</li>
</ul>
<form ng-submit="submitSite()">
<label>Site url: <input type="url" ng-model="newSite.url" /></label>
<p>Groups:
<label ng-repeat='group in groups'>
<input type="checkbox" name="group-check" value="{{group.name}}" id="{{group.id}}"
ng-model="checkedGroupIds[group.id]" />
{{group.name}}
</label>
</p>
<input type="submit" id="submitWebsite" value="Save Changes" ng-disabled="!newSite.url" />
</form><!-- end submitSite() -->
</div>
<div id="group-form">
<form ng-submit="submitGroup()">
<label>Name of the group: <input ng-model="newGroup.name" /></label>
<input type="submit" class="btn btn-primary" id="submitGroup" value="Save Changes"
ng-disabled="!newGroup.name"/>
</form><!-- end submitGroup() -->
</div>

AngularJS - Using ng-repeat twice under the same controller

I have the following DIV:
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select name="userSelect">
<div ng-repeat="user in users">
<option value="{{user.id}}">{{user.name}}</option>
</div>
</select>
<input type="submit" value="add">
</form>
</div>
This is my controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"Username1","roles":[{}]},
{"id":"1","name":"Username2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
/*
$.post({}); //Push changes to server
*/
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
I can see the first ng-repeat is working fine and is listing the user.id and user.name, however the second ng-repeat (the one inside the form) does not display the information, is that related to the fact that I've already looped through that element in the previous div?
You misused the select directive :
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users">
http://docs.angularjs.org/api/ng.directive:select

Resources