Select all options from dropdown on button click using AngularJS - html

I want to select all values from a drop down of HTML on ng-click. Here is my HTML code
<select multiple ng-model="selectedToPostalCodes"
ng-options="items.postalcode for items in toPostalCodes">
<option style="display:none;"></option>
</select>
<input type="button" value="Select All" ng-click="selectall()">
So I want the implementation of selectall() function.
Thanks

you can try this way:: Fiddle
fiddleApp.controller('Main', ['$scope', function($scope) {
$scope.toPostalCodes = [
{postalcode:1, name:"Japan"},
{postalcode:4, name:"USA"}
];
$scope.selectedToPostalCodes = [];
$scope.selectall = function(){
$scope.selectedToPostalCodes = [];
angular.forEach($scope.toPostalCodes, function(item){
$scope.selectedToPostalCodes.push( item.postalcode);
});
}
}]);

You can try like this:
$scope.selectall = function() {
var allOptions = [];
// First get all codes as list
angular.forEach($scope.toPostalCodes, function(item) {
allOptions.push(item.postalcode);
});
// And then assign the values to the scope model
$scope.selectedToPostalCodes = allOptions;
};

Related

Display Multiple values selected from dropdown in a List

I have a angularjs function which contain an array of values as follows
$scope.arrayVal = function()
{
var array = [{id:1,name:"one"},{id:2,name:"two"}];
}
I am passing this array to my dropdown which is in the html page and show the values in a dropdown as follows
<html>
<select ng-model="data.selected">
<option value="item.id,item.name" ng-repeat="item in array">{{item.id}} {{item.name}}</option>
</html>
What I want to achieve is I want to make user select multiple values from the dropdown and these selected values should be displayed according to the selected order below the dropdown. How can I achieve this with angularjs and html only. (I am not using any libraries other than angularjs)
Try this plunker https://next.plnkr.co/edit/6Nxaxz9hGNXospyT. You might have to tinker with it to get the outcome you want
<div ng-controller="ctrl">
<select ng-model="selectedItem" ng-options="item.name for item in items" ng-change="selectItem()">
</select>
<p ng-repeat="item in selectedItems">{{item.id}} - {{item.name}}</p>
</div>
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.items = [{id:1,name:"one"},{id:2,name:"two"}];
$scope.selectedItems = [];
$scope.selectedItem;
$scope.selectItem = function () {
var index = $scope.selectedItems.findIndex(function (fItem) { return $scope.selectedItem.id === fItem.id; });
console.log(index)
if (index > -1) $scope.selectedItems.splice(index, 1);
else $scope.selectedItems.push($scope.selectedItem);
};
});

AngularJS - Multiple Dropdowns

I'm currently working on a project where I have a button that adds a dropdown everytime you click on the button.
Clicking the button not only shows the dropdown, but also a "Remove item" button, where you can remove the respective item added.
Then if you select an option from the dropdown, it will show another dropdown with more options, depending on what you chose on the first dropdown.
You can choose from the dropdown two options, movies or games.
And then on the second dropdown should appear a movie list or a game list depending on what you selected.
You can see HERE the current fiddle.
index.html:
<div ng-app="myApp" ng-controller="testCtrl">
<button ng-click = "addNewItem()">Add new Item</button>
<div ng-repeat="item in itemSet.item track by $index">
<button ng-click = "removeItem($index)">Remove item</button>
<select ng-model="category"
ng-change="changeCategory(category)"
ng-options="category as category for category in categoryTypes">
<option></option>
</select>
<select ng-show="movieSelected"
ng-model="movieType"
ng-options="movie as movie for movie in movieCategories">
<option></option>
</select>
<select ng-show="gameSelected"
ng-model="gameType"
ng-options="game as game for game in gameCategories">
<option></option>
</select>
</div>
</div>
app.js:
var myApp = angular.module('myApp', []);
myApp.controller('testCtrl', ['$scope', function ($scope) {
$scope.categoryTypes = ['Movies', 'Games'];
$scope.gameCategories = ['RPG', 'Sports'];
$scope.movieCategories = ['Action', 'SciFi'];
$scope.itemSet = { item : [] };
$scope.itemSet.item = [];
$scope.gameSelected = false;
$scope.movieSelected = false;
$scope.addNewItem = function () {
$scope.itemSet.item.push('');
};
$scope.removeItem = function (index) {
$scope.itemSet.item.splice(index, 1);
};
$scope.changeCategory = function(category) {
if(category == 'Movies') {
$scope.gameSelected = false;
$scope.movieSelected = true;
} else {
$scope.gameSelected = true;
$scope.movieSelected = false;
}
};
}]);
There are some things that are going wrong with this. With no order in particular:
For example, if I added 3 items, and then want to delete the first one, it will delete the third, then the second and finally the first if you keep pressing the "Remove Item" button.
If I add 3 items and I select "movies" from the first dropdown on the first row for example, it will display all of the other dropdowns with the possibility of choosing the items from the movie list on all of them, even if I didn't choose anything from the other rows.
Also if you want to add, lets say, 2 items, in one item you pick first "movies" and then on the second one you pick "games", the "extra" dropdowns will show the list of games instead of the respective list of items for each of the cases.
The actual project works similar to this, but with 4 dropdowns, and the information comes from a database but I guess that with the Fiddle should be enough to get the idea and to take a possible solution to the actual project.
If someone could help me out on this one I'll be very gratefull!
Your code has a big problem that is: you have the same ngModel for all items in ngRepeat.
After fixing this, you can simplify a lot your code.
You don't need to use ngChange to know what category is selected, you can simply use ngSwitch directive what fits well in this case.
See it working:
(function() {
'use strict';
angular
.module('myApp', [])
.controller('testCtrl', testCtrl);
testCtrl.$inject = ['$scope'];
function testCtrl($scope) {
$scope.categoryTypes = ['Movies', 'Games'];
$scope.gameCategories = ['RPG', 'Sports'];
$scope.movieCategories = ['Action', 'SciFi'];
$scope.itemSet = {
item: []
};
$scope.addNewItem = function() {
$scope.itemSet.item.push({});
};
$scope.removeItem = function(index) {
$scope.itemSet.item.splice(index, 1);
};
}
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="testCtrl">
<button ng-click="addNewItem()">Add new Item</button>
<div ng-repeat="item in itemSet.item track by $index">
<button ng-click="removeItem($index)">Remove item</button>
<select ng-model="item.category"
ng-options="category for category in categoryTypes">
<option value hidden>Select a category</option>
</select>
<span ng-switch="item.category">
<select ng-switch-when="Movies"
ng-model="item.movie"
ng-options="movie for movie in movieCategories">
<option value hidden>Select a movie</option>
</select>
<select ng-switch-when="Games"
ng-model="item.game"
ng-options="game for game in gameCategories">
<option value hidden>Select a game</option>
</select>
</span>
</div>
<pre ng-bind="itemSet.item | json"></pre>
</div>
</body>
</html>
The main problem is you're controls are bound $scope values instead of the individual items you are trying to manipulate. A secondary problem is that you initialize each new array element as an empty string '' instead of an object {}.
This will work:
index.html
<div ng-app="myApp" ng-controller="testCtrl">
<button ng-click = "addNewItem()">Add new Item</button>
<div ng-repeat="item in itemSet.item track by $index">
<button ng-click = "removeItem($index)">Remove item</button>
<select ng-model="item.category"
ng-change="changeCategory(item)"
ng-options="category as category for category in categoryTypes">
<option></option>
</select>
<select ng-show="item.movieSelected"
ng-model="movieType"
ng-options="movie as movie for movie in movieCategories">
<option></option>
</select>
<select ng-show="item.gameSelected"
ng-model="gameType"
ng-options="game as game for game in gameCategories">
<option></option>
</select>
</div>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('testCtrl', ['$scope', function ($scope) {
$scope.categoryTypes = ['Movies', 'Games'];
$scope.gameCategories = ['RPG', 'Sports'];
$scope.movieCategories = ['Action', 'SciFi'];
$scope.itemSet = { item : [] };
$scope.itemSet.item = [];
$scope.gameSelected = false;
$scope.movieSelected = false;
$scope.addNewItem = function () {
$scope.itemSet.item.push({});
};
$scope.removeItem = function (index) {
$scope.itemSet.item.splice(index, 1);
};
$scope.changeCategory = function(item) {
if(item.category == 'Movies') {
item.gameSelected = false;
item.movieSelected = true;
} else {
item.gameSelected = true;
item.movieSelected = false;
}
};
}]);
Updated fiddle:https://jsfiddle.net/5zwsdbr0/

select control loses all options after ng-select

I have a select box like this...
<select class="form-control m-b"
ng-options="portfolios.id as portfolios.product_name for portfolios in portfolio"
data-ng-model="portfolio" ng-change="getPriceAttributes()">
</select>
When a user selects an option from the select box, the function getPriceAttributes() is called...
(function() {
var app = angular.module('QuoteApp');
var quoteBuilderController = function($scope, $http) {
$scope.formData = {};
// this populates the select
$http.get('scripts/json/sample-products.json')
.then(function(res){
$scope.portfolio = res.data.Connectivity;
});
//this is called when a user selects an option from the select control
$scope.getPriceAttributes = function() {
$http.get('scripts/json/sample-product-attribute-response.json')
.then(function(res){
$scope.formFields = res.data;
});
};
};
app.controller('quoteBuilderController', ['$scope', '$http', quoteBuilderController]);
}());
When I load the page, the select box has a list of options which come from a json file. When I select an option from the select box, getPriceattributes() is called, but the options in the select box disappear, leaving an empty select control. Does anyone know why this might be happening?
Thank you

How to clear input fields in Angularjs after click of a button

I need to clear a textbox and a select-list after a button is clicked.This is what I tried but it doesn't seems to work:
HTML:
<input type="text" ng-model="Model.CurrentDowntimeEvent.Comment" size="60" placeholder="ENTER IN ANY ADDITIONAL INFORMATION"/><br>
<select class="categories" ng-disabled="selectlistdisabled" ng-model="Model.CurrentDowntimeEvent.CategoryId" ng-options="downtimeCategory.CategoryId as downtimeCategory.CategoryName for downtimeCategory in Model.DowntimeCategories">
</select>
<button ng-click="StopCurrentDowntime()">Stop Downtime Event</button>
JS:
angular.module('myApp', [])
.controller('DowntimeController', function ($scope, $http) {
$scope.Model = new Model($http);
$scope.StopCurrentDowntime = function () {
$scope.CurrentDowntimeEvent.Comment = '';
$scope.CurrentDowntimeEvent.CategoryId = '';
}
});
Instead of using button to clear input fields you can use reset (input type="reset") inside the form
You are missing Model. in your JS
angular.module('myApp', []).controller('DowntimeController', function ($scope, $http) {
$scope.Model = new Model($http);
$scope.StopCurrentDowntime = function () {
$scope.Model.CurrentDowntimeEvent.Comment = '';
$scope.Model.CurrentDowntimeEvent.CategoryId = '';
}
});

sending konckoutjs ViewModel as data throught ajax

for populating search form with data i'm using following ViewModel:
function AppViewModel() {
var self = this;
self.Countries =[{"id": "1","name": "Russia"},{"id": "2","name": "Qatar"}];
self.selectedCountryId =ko.observable();
}
I need Countries list for populate dropdwonlist.
When user fills the form and clicks "send", i need to submit the data, but i do not need to send the Countries list!
(only SelectedCountryId)
var vm=new AppViewModel();
ko.applyBindings(vm);
$('button').click(function(){
console.log(ko.mapping.toJSON(vm));
});
Is there the way to get rid of countries list without build new ViewModel for sending?
Observables are just like normal functions, so you just need to call it from outside.
function AppViewModel() {
var self = this;
self.Countries =[{"id": "1","name": "Russia"},{"id": "2","name": "Qatar"}];
self.selectedCountryId = ko.observable('1');
}
$(function() {
var vm = new AppViewModel();
ko.applyBindings(vm);
$('button').click(function(){
console.log(vm.selectedCountryId()); // plain
console.log(ko.toJSON(vm.selectedCountryId())); // json
});
});
​
http://jsfiddle.net/DiegoVieira/6kZMj/4/
Please take a look into this demo I've created for you Click here for the DEMO
Updated Demo Click here for the updated Demo
HTML Code
<select data-bind="options: countries, optionsText: 'name', optionsValue: 'id', value: selectedChoice, optionsCaption: 'Choose..'"></select>
<br/>
<label data-bind="text: selectedChoice"></label>
Javascript Code
var CountryModel = function(data){
var self = this;
self.id = ko.observable(data.id);
self.name = ko.observable(data.name);
};
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.countries = ko.observableArray([
new CountryModel({id: "1", name: "Russia"}),
new CountryModel({id: "2", name: "Qatar"})]);
};
ko.applyBindings(new viewModel());
START UPDATE
What is updated:
HTML Code:
Added button on event Click it calls sendMe function which returns json object of selectedCountryId
<input type="button" data-bind="click: sendMe, enable: selectedChoice" Value="Click Me"/>
Javascript Code
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
END UPDATE
START UPDATE1
This is update for the last comment, regarding avoid addition model, in this case let's skip CountryModel
So, the Javascript Code will be the following:
var viewModel = function(data) {
var self = this;
self.selectedChoice = ko.observable();
self.countries = ko.observableArray([
{id: "1", name: "Russia"},
{id: "2", name: "Qatar"}]);
self.sendMe = function(){
alert(ko.toJSON({ selectedCountryId: this.selectedChoice()}));
};
};
ko.applyBindings(new viewModel());
END UPDATE1
Hope, it will help you.
Thanks.