Select first value from select box by default - AngularJS - angularjs

I have two select boxes. The second select box populates from first select box.
I have applied a filter for the second select box to populate as per the options selected in first select box. The second select box populates from an array var outputformats = [];
This is my code
HTML
<select name="reporttype"id="reporttype"
ng-init="reporttype='1115'"
ng-model="reporttype">
<option value="1115">Previous Day Composite Report</option>
<option value="1114">ACH Receive</option>
</select>
<select name="outputformat" id="outputformat"
ng-model="outputformat"
ng-options="format for format in outputformats | outputformatfilter: reporttype:this">
</select> Value : {{outputformat}}
Filter
angular.module('myApp.outputformatfilter',[])
.filter('outputformatfilter', function () {
return function (input,selectedreport,scope) {
var outputFormatReport = {"1115":"HTML,PDF","1114":"CSV,EXCEL"};
var outputformats = outputFormatReport[selectedreport].split(',');
return outputformats;
};
});
Now what I want is whenever the options in second select box changes, its first option should be selected by default, that is the first option from the array should be selected by default.
UPDATE:
Updated fiddle, added ng-if= reporttype !== '' to second select box
FIDDLE

On your controller, watch the filtered options and act on that:
function myController ($scope) {
// watch the filtered output formats
$scope.$watchCollection("filteredOutputFormats", function(val) {
// select the first one when it changes
$scope.outputformat = val[0];
});
}
Make sure you assign the filtered results to a $scope variable:
<select name="outputformat" id="outputformat"
ng-model="outputformat"
ng-options="format for format in filteredOutputFormats = (outputformats | outputformatfilter: reporttype:this)">
</select>
JSFIDDLE

Try this:-
var myApp = angular.module('myApp',['myApp.outputformatfilter']);
myApp.controller('mainController',function($scope,$filter){
var outputformats = [];
$scope.outputFormatReport = {"1115":"HTML,PDF,CSV,EXCEL","1114":"PHP,HTML,PDF","default":"CSV,HTML"};
$scope.$watch('reporttype', function (newValue, oldValue, scope) {
outputformats = $scope.outputFormatReport[newValue].split(',');
$scope.outputformat=outputformats[0]
});
});
angular.module('myApp.outputformatfilter',[]).filter('outputformatfilter', function () {
return function (input,selectedreport,scope) {
console.log('input is '+input+' \nReport is '+selectedreport);
console.log(scope.outputFormatReport);
if(selectedreport!= undefined){
var outputformats =
console.log( scope.outputFormatReport[selectedreport]);
outputformats = scope.outputFormatReport[selectedreport].split(',');
console.log(outputformats);
}else{
return {};
}
return outputformats;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="mainController">
<select name="reporttype"id="reporttype" ng-init="reporttype='1115'" ng-model="reporttype">
<option value="1115">Previous Day Composite Report</option>
<option value="1114">ACH Receive</option>
</select>
<select name="outputformat" id="outputformat" ng-model="outputformat" ng-options="format for format in outputformats | outputformatfilter: reporttype:this">
</select> Value : {{outputformat}}
</div>
</body>

Related

AngularJS filter (object and multiple values) not working

So I got a project which is using AngularJS with UI-Router, I iterate through a json which has a property called "state" which is what I want to use as a filter, however, I will be using a "selector" where I can pick "All" or a specific one.
I'm new to AngularJS So not sure exactly what is not working, this is the code I have so far:
function filterState (installment){
switch(selectedValue) {
case 1:
if(installment.state === 'PAID'){
return installment;
}
break;
case 2:
if(installment.state === 'LATE'){
return installment;
}
break;
case 3:
if(installment.state === 'PENDING'){
return installment;
}
break;
default:
return installment;
}
The filter however is not working as it should
Here is how I'm calling it:
<div class="row" ng-repeat="installment in vm.clients.installments | filter: filterState">
Not sure exactly what is the error, when I filter by a value manually like filter: {state:'PAID'}
It works
If you need to filter with a select option then you can do something like this:
<select name="select" id="select" ng-model="clients.status">
<option value="PAID">PAID</option>
<option value="LATE">LATE</option>
<option value="PENDING">PENDING</option>
<option value="ALL">ALL</option>
</select>
<div class="row" ng-repeat="installment in clients.installments | filter: filterState">
{{installment.id}}
</div>
And in controller the function to filter:
$scope.filterState = function(installment) {
if ($scope.clients.status === 'ALL') return true;
return $scope.clients.status === installment.status;
};
When option ALL is selected, it shows all the items of the list
Check a working demo here: DEMO
Apparently I needed to return a boolean value instead of the object, I did try that before, but my other issue was that I was calling the function directly instead of doing vm.function (once passed to the context), after doing that it worked.
Filter function returns an iterator function. like callback. Please check below example.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.criteria = { name: 'Bob'};
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};
$scope.items =[
{ name: 'Bob'},
{ name: 'Alice'}
];
});
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
Credit: Anonymous

Unable to fill Dropdown list

I am filling 3 Dropdown lists using Angular js
Based on first dropdown selection , second dropdown will fill, and based on second dropdown third dropdown will fill.
HTML
<div ng-app ng-controller="myCtrl">
<select ng-model="option1" ng-options="option for option in options1" ng-change="getOptions2()">
</select>
<select ng-model="option2" ng-options="option for option in options2" ng-change="getOptions3()">
</select>
<select ng-model="option3" ng-options="option for option in options3">
</select>
</div>
Controller
var option1Options = ["Men", "Women", "Kids"];
var option2Options = [["Top wear","Bottom wear","Blazers"],
["W-Top Wear","W-Bottom Wear","W-Blazers"],
["K-Top wear","K-Bottom wear","K-others"]];
var option3Options = [["M-Tshirts","M-Casula Shirts","option2 - 3-3"],
["M-Jeans","option2 - 3-2","option2 - 3-3"],
["M-Blazers","option2 - 3-2","option2 - 3-3"],
["w-Tshirts","w-Casula Shirts","w-option2 - 3-3"]];
function myCtrl($scope){
$scope.options1 = option1Options;
$scope.options2 = [];
$scope.options3 = [];
$scope.getOptions2 = function(){
var key = $scope.options1.indexOf($scope.option1);
var myNewOptions = option2Options[key];
$scope.options2 = myNewOptions;
};
$scope.getOptions3 = function(){
var key = $scope.options2.indexOf($scope.option2);
var myNewOptions = option3Options[key];
$scope.options3 = myNewOptions;
};
}
Fiddle Link : http://jsfiddle.net/mayankBisht/Xku9z/513/
Problem
When I am trying to fill third dropdown with womens options, it's still showing Mens options.
Please help.

Remove select options based on button click in angular js

In my app i have a select html which has following options
"Addition","Deletion","Duplicate","Member Duplicate"
Above drop down page is common for both add and edit screen. As of now if we come from any addition click or edit click drop-down has all options. (Note: drop-down binds at the time of loading page itself. we will show/hide depending on click)
As per new requirement I need to remove all other options except "Addition" in addition click and remove "Addition" option in edit click.
select html:
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
Js
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member); };
Please let me know if you need more details from my end.
Update :
Here the full sample code and working demo with dummy data.
HTML
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<select name="ReasonID" required ng-model="member.ReasonID" class="form-control" ng-options="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description"></select>
<br/>
<input type="button" ng-click="manageMember(undefined)" value="add"/>
<input type="button" ng-click="manageMember('bla bla bla')" value="edit"/>
</div>
</div>
JS
function TodoCtrl($scope) {
$scope.reasons = [{ID:1,Description :"Addition"}, {ID:2,Description :"Deletion"},{ID:3,Description :"Duplicate"},{ID:4,Description :"Member Duplicate"}];
var reasonsTemp =angular.copy($scope.reasons);
$scope.manageMember = function (member) {
console.log(reasonsTemp)
$scope.reasons=reasonsTemp;// assign global object to model
$scope.showGrid = false;
$scope.showForm = true;
$scope.memberTemp = member;
var EditArray=[];
for(var i = 0 ; $scope.reasons.length>i;i++)
{
if($scope.reasons[i].Description === ($scope.memberTemp == undefined ? "Addition" : "bla bla bla"))// condition for is this addition or not
{
EditArray = $scope.reasons[i];
break;
}
else // if is it not addition, then addition only offect that object. because we were already assigned original value globally
{
if($scope.reasons[i].Description!=="Addition")
{
EditArray.push($scope.reasons[i])
}
}
}
$scope.reasons=EditArray;
console.log($scope.reasons);
}
}
Working Demo On console window
Try this,
HTML
<select ng-model="selectedOption">
<option ng-show="reason.show" ng-repeat="reason.ID as reason.Description for reason in reasons |orderBy: reason.Description">{{reason.ID}}</option>
</select>
JS
$scope.manageMember = function (member) {
$scope.showGrid = false;
$scope.showForm = true;
reset();
$scope.memberTemp = member;
angular.extend($scope.member, member);
if(member){
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = true;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = false;}
}
}else{
for(var i = 0 ; $scope.reasons.length>i;i++)
{
$scope.reasons[i].show = false;
if($scope.reasons[i].ID == "Addition"){$scope.reasons[i].show = true;}
}
}
}
Suppose you have two buttons as,
<input type="button" ng-click="toAdd=true">Add</input>
<input type="button" ng-click="toAdd=false">Edit</input>
And the select box code should be like,
<select ng-model="selectedOption">
<option ng-show="toAdd">Addition</option>
<option ng-show="!toAdd">Deletion</option>
<option ng-show="!toAdd">Duplicate</option>
<option ng-show="!toAdd">Member Duplicate</option>
</select>
Hope this helps.

angular js filter/search and unique selects

I've tried most of the SO answers for identifying unique values in angular.js ( i am a novice) but my problem is trying to get these into a select form and for that to have a filter on the data in a table.
essentially i have some data, I want to display it in a table and in the table header have a select dropdown of unique values in that column of data and be able to filter the table displayed by values selected.
I'm trying to use
app.filter('unique', function () {
return function ( collection, keyname) {
var output = [],
keys = []
found = [];
if (!keyname) {
angular.forEach(collection, function (row) {
var is_found = false;
angular.forEach(found, function (foundRow) {
if (foundRow == row) {
is_found = true;
}
});
if (is_found) { return; }
found.push(row);
output.push(row);
});
}
else {
angular.forEach(collection, function (row) {
var item = row[keyname];
if (item === null || item === undefined) return;
if (keys.indexOf(item) === -1) {
keys.push(item);
output.push(row);
}
});
}
return output;
};
});
and my html looks like this
<th> Number:
<br/>
<select ng-model="search.number"
ng-options="row.numberfor row in data | unique:'number'">
<option value=""> </option>
</select>
</th>
and then the table data itself
</tr>
</thead>
<tbody>
<tr ng-repeat="r in data | filter:{ number: search.number, }">
<td> {{r.number}}</td>
</tr>
</tbody>
</table>
The output generates this, but the value isn't set correctly so filtering returns nothing (as 0,1,2,3.. have not matching rows of data).
<select ng-model="search.number"
ng-options="row.numberfor row in data | unique:'number'"
class="ng-pristine ng-valid">
<option value="" class=""> </option>
<option value="0">1023 456789</option>
<option value="1">1024 456789</option>
<option value="2">1025 456789</option>
<option value="3">1023 111999</option>
<option value="4">1024 111999</option>
</select>
I've also tried this unique function
/*
app.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i][key]);
}
}
return uniqueList;
};
}); */
but no joy. i had to add [key] to this line uniqueList.push(input[i][key]); just to get the values displayed in the drop down, but I can't seem to control the values of the options in that drop down.
I have no errors in my console.
I have 10 columns/fields to filter on, but I've just included one example here.
Can someone help point me in the right direction. thanks
edit:
I see this directive might be useful, but when the map key->value are the same, is there a quicker/easier way?
app.directive('mySelect', [function () {
return {
restrict: 'E',
transclude: true,
replace: true,
template: '<select ng-options="key as value for (key, value) in myMap" ng-transclude></select>',
link: function postLink(scope, element) {
scope.myMap = {"1":"1","2":"2","3":"3"};
// e.g. hashmap from server
}
};
turns out this works
<select ng-model="search.<?php echo $column; ?>"
ng-options="v for (k, v) in data
| orderBy:'<?php echo $column;?>'
| unique:'<?php echo $column;?>' ">
<option value="">select</option>
</select>
stuck within a foreach that looks at the each of columns in a CSV file.
i.e. the full excel style filtering with any csv passed in.

AngularJS-Want unique filter to be applied only to dropdown and not to the ng-repeat results

Tried the solution given in Showing unique dropdown options in Angularjs
<select ng-model="categorySelected" ng-options="c.category for c in accounts|unique:'category'">
</select>
<div ng-repeat="c in accounts| filter:categorySelected">
.........
</div>
app.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});
I also tried
<div ng-repeat="c in accounts| filter:{templateCategory: categorySelected}">
I have rows fetched from the table and is getting displayed on the html. I want to list unique categories from the result in dropdown. But on selection, i want all the rows belonging to that category to be listed. Now i get the unique categories in the dropdown but even the ng-repeat results show only the unique results which should not be the case. Please help.
I suspect the problem is in the use of filter in ngRepeat.
1) Use as to set categorySelected to the value of the category selected in the dropdown...
<select ng-model="categorySelected"
ng-options="a.category as a.category for a in accounts | unique:'category'">
</select>
2) User filter: { category: categorySelected } in ngRepeat to filter accounts by category based on the current value of categorySelected...
<div ng-repeat="a in accounts | filter : {category: categorySelected}">
{{ a.name }}
</div>
JSFiddle

Resources