Angularjs: Populating the drop-down as per user input - angularjs

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>

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();
});

show no data available message when ng-options is empty in select?

I have created an select element as
<label class="item item-select no-border-bottom padding full-width custom-back">
<div class="input-label">Select Time Slot</div>
<select ng-model="addAppointment.timeSlot" name="timeSlot" class="custom-back" ng-disabled="!addAppointment.date" ng-options="timeSlot as timeSlot for timeSlot in availableTimeSlots" required>
</select>
</label>
I would like a option having message No Data in select when ng-options array is empty.
You could add an <option> with ng-if to your select. Here is a contrived example of how this would work.
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.options = [];
$scope.selectedOption = undefined;
$scope.addOptions = function() {
var start = $scope.options.length;
for(var i = 1; i <= 5; i++) {
$scope.options.push('Option #' + (start + i));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="selectedOption" ng-options="opt as opt for opt in options">
<option value="" ng-if="options.length === 0">No Data</option>
</select>
<button type="button" ng-click="addOptions()">Add Options</button>
</div>

How to handle multiple forms present in a single page using AngularJS

I am a newbie in AngularJS. I am having multiple forms on a single page which gets displayed based on the user selection only one at a time.
The DOM has two child controllers namely FirstFormController, SecondFormController wrapped under a parent controller named XceptionController.
A parent controller function is used to submit the form data from both the children. The form data is saved on to the parent controller's scope.My HTML looks like below
<div ng-app="app">
<div class="container" ng-controller="XceptionController">
<form class="form-container">
<select id="select-form" ng-change=selectForm() ng-model="selectedForm">
<option value="select" disabled selected>Select an Option</option>
<option value="firstform">Get Firstname</option>
<option value="secondform">Get Lastname</option>
</select>
</form>
<div ng-controller="FirstFormController" class="firstform" ng-show="fname">
<form name="firstnameform">
<input type="text" name="firstname" ng-model="form.firstname" id="firstname">
<label for="#firstname">Firstname</label>
</form>
<div class="content" ng-show="fname">
<p>Firstname is {{form.firstname}}</p>
</div>
</div>
<div ng-controller="SecondFormController" class="secondform" ng-show="lname">
<form name="lastnameform">
<input type="text" name="lastname" ng-model="form.lastname" id="lastname">
<label for="#lastname">Lastname</label>
</form>
<div class="content" ng-show="lname">
<p>Lastname is {{form.lastname}}</p>
</div>
</div>
<button ng-click="submitForm(form)">Submit</button>
And my js looks like
var app = angular.module('app', []);
app.controller('XceptionController', function($scope){
$scope.form = {};
$scope.selectedForm = '';
$scope.selectForm = function() {
$scope.lname = 0;
$scope.fname = 0;
var foo = angular.element(document.querySelector('#select-form')).val();
if(foo == 'firstform') {
$scope.fname = 1;
}
else if(foo == 'secondform'){
$scope.lname = '1';
}
};
$scope.submitForm = function(form){
//form data
console.log(form);
};
});
app.controller('FirstFormController', function($scope){
$scope.firstname = "";
});
app.controller('SecondFormController', function($scope){
$scope.lastname = "";
});
But on submitting the form I get the data from both the forms since I set it on the parent's scope. Is there a way by which I can submit the form and get the form data only for the form which is currently displayed. This fiddle will help you more in understanding my question. https://jsfiddle.net/xmo3ahjq/15/
Also help me in knowing if my code is properly written the way it should be or is there a better way to implement this. Should the form submission code be placed under a separate angular service ?
var app = angular.module('app', []);
app.controller('XceptionController', function($scope) {
$scope.form = {};
$scope.selectedForm = null;
$scope.selectForm = function() {
// reset the form model object
$scope.form = {};
};
$scope.isSelected = function(formName) {
return $scope.selectedForm === formName;
};
$scope.submitForm = function(form) {
// form data
console.log(form);
};
});
app.controller('FirstFormController', function($scope) {
});
app.controller('SecondFormController', function($scope) {
});
<div ng-app="app">
<div class="container" ng-controller="XceptionController">
<form class="form-container">
<select id="select-form" ng-change=selectForm() ng-model="selectedForm">
<option value="" disabled selected>Select an Option</option>
<option value="firstform">Get Firstname</option>
<option value="secondform">Get Lastname</option>
</select>
</form>
<div ng-controller="FirstFormController" class="firstform" ng-show="isSelected('firstform')">
<form name="firstnameform">
<input type="text" name="firstname" ng-model="form.firstname" id="firstname">
<label for="#firstname">Firstname</label>
</form>
<div class="content">
<p>Firstname is {{form.firstname}}</p>
</div>
</div>
<div ng-controller="SecondFormController" class="secondform" ng-show="isSelected('secondform')">
<form name="lastnameform">
<input type="text" name="lastname" ng-model="form.lastname" id="lastname">
<label for="#lastname">Lastname</label>
</form>
<div class="content">
<p>Lastname is {{form.lastname}}</p>
</div>
</div>
<button ng-click="submitForm(form)">Submit</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

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].

how can we get the array id of selected checkbox in 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;
});

Resources