Issue with Angular JS - angularjs

I am a UI developer and I am completely new to Angular, however, I understand jQuery. I have joined a new company and they use Angular JS with JAVA. I have been assigned a task over which I am banging head for the past few days. I've come under the scanner now.
Basically I have a table in .html page to which data is coming (Sorry, I am told that I would need atleast 10 reputation to post a screen shot). Now I want to other column in that table.
I have tried adding that column in columns_panel.js but still it is not coming in the grid by default.
I understand that my question is not clear over here, but trust me, even my Team lead is also not willing to disclose any thing.
Can any JS guru's be help to me?
<div columns-panel columns="columns" show-panel="showColumnsPanel"></div>
<table class="responsive">
<thead>
<tr>
<th>
</th>
<th class="isFlagged">
<div class="flag"></div>
</th>
<th ng-repeat="column in columns" ng-click="sortBy(column)" class="{{ column }}">
<a class="th-inner">
{{ column | translate }}
<span ng-show="isSortColumn(column)"
ng-class="{'sort-icon-desc': !isSortAscending(),
'sort-icon-asc': isSortAscending()}">
</span>
</a>
</th>
<!--<th class="toggle-columns-header">-->
<!--<a class="th-inner" ng-click="showColumnsPanel = !showColumnsPanel">+</a>-->
<!--</th>-->
</tr>
</thead>
<tbody>
<tr ng-repeat="dispute in disputes.currentPage"
ng-class="isSelected(dispute) ? '{{ dispute | disputeTrClass }} checked-dispute' : '{{ dispute | disputeTrClass }}'"
ng-click="goToDisputeDetails(dispute)">
<td ng-class="isNegative(dispute) ? 'select-dispute alert-corner' : 'select-dispute'" ng-click="$event.stopPropagation()">
<input id="select-dispute-{{ dispute.id }}" type="checkbox" ng-click="toggleSelectedDispute(dispute)" ng-checked="isSelected(dispute)" ng-disabled="!dispute.isFlaggable" ng-hide="!dispute.isFlaggable" />
<label for="select-dispute-{{ dispute.id }}" ng-hide="!dispute.isFlaggable"></label>
</td>
<td class="isFlagged" ng-click="toggleFlag(dispute, $event)">
<div ng-show="dispute.isFlaggable" class="flag {{ dispute.isFlagged ? 'flagged' : 'unflagged' }}"></div>
</td>
<td ng-repeat="column in columns" class="{{ column }}">
<div data-ng-switch data-on="column">
<div data-ng-switch-when="reason">
{{ dispute[column] }}
<span class="reason-code" ng-if="dispute.reason !== 'N/A'">{{ dispute.reasonCode }}</span>
</div>
<div data-ng-switch-when="status">
{{ dispute[column]=="Urgent Response Required"?"Response Required":dispute[column] }}
</div>
<div data-ng-switch-when="amount">
<div ng-if="isNegative(dispute)" class="negative">
-<span class="currency">$</span>{{ dispute[column] * -1 | number:2 }}
</div>
<div ng-if="isPositive(dispute)">
<span class="currency">$</span>{{ dispute[column] | number:2 }}
</div>
</div>
<div data-ng-switch-when="dateReceived">
{{ dispute[column] | translatedDate }}
</div>
<div data-ng-switch-when="respondBy">
{{ dispute[column] | translatedDate }}
</div>
<div data-ng-switch-when="respondedOn">
{{ dispute[column] | translatedDate }}
</div>
<div data-ng-switch-default>
{{ dispute[column] }}
</div>
</div>
</td>
<!--<td class="{{ columns[columns.length - 1] }}"></td>-->
</tr>
</tbody>
</table>
<!-- No Disputes To Display -->
<div disputes-table-empty></div>
<!-- Error Message -->
<div disputes-table-error></div>
<style type="text/css">
.status {
padding-left: 27px !important;
}
</style>
This is the Model
DisputeModule.value('Dispute', function (attributes) {
this.id = attributes.id;
this.amount = attributes.amount;
this.cancelDate = attributes.cancelDate;
this.cancellationNumber = attributes.cancellationNumber;
this.cancelZone = attributes.cancelZone;
this.cardDeposit = attributes.cardDeposit;
this.cardMemberName = attributes.cardMemberName;
this.cardNumber = attributes.cardNumber;
this.chargeAmount = attributes.chargeAmount;
this.chargeDate = attributes.chargeDate;
this.creditReceived = attributes.creditReceived;
this.dateReceived = attributes.dateReceived;
this.disputeNumber = attributes.disputeNumber;
this.description = attributes.description;
this.isFlaggable = attributes.isFlaggable;
this.isFlagged = attributes.isFlagged;
this.locationID = attributes.locationID;
this.merchandiseReturned = attributes.merchandiseReturned;
this.merchandiseType = attributes.merchandiseType;
this.merchantAccount = attributes.merchantAccount;
this.modeOfReturn = attributes.modeOfReturn;
this.originalCardNbr = attributes.originalCardNbr;
this.payeeLocationId = attributes.payeeLocationId;
this.payeeSENbr = attributes.payeeSENbr;
this.reason = attributes.reason;
this.reasonCode = attributes.reasonCode;
this.referenceNumber = attributes.referenceNumber;
this.reservationCanceled = attributes.reservationCanceled;
this.reservationCanceledDate = attributes.reservationCanceledDate;
this.stage = attributes.stage;
this.status = attributes.status;
});
This is the columns_panel.js
DisputeModule.directive('columnsPanel', function (BASE_URL) {
var defaultColumns = [
'disputeNumber',
'status',
'dateReceived',
'respondBy',
'respondedOn',
'type',
'reason',
'cardNumber',
'originalCardNbr',
'transactionDate',
'referenceNumber',
'resolution',
'merchantAccount',
'locationID',
'payeeSENbr',
'payeeLocationId',
'chargeAmount',
'amount'
];
var availableColumns = [
'disputeNumber',
'status',
'dateReceived',
'respondBy',
'respondedOn',
'type',
'reason',
'cardNumber',
'originalCardNbr',
'transactionDate',
'referenceNumber',
'resolution',
'merchantAccount',
'locationID',
'payeeSENbr',
'payeeLocationId',
'chargeAmount',
'amount'
];
var columns = defaultColumns.slice();
return {
templateUrl: BASE_URL + '/resources/views/columns_panel.html',
scope: {
columns: '=',
showPanel: '='
},
controller: function ($scope) {
function addColumn(column) {
var tmpColumns = $scope.columns.slice();
tmpColumns.push(column);
tmpColumns.sort(function (a, b) {
return $scope.availableColumns.indexOf(a) - $scope.availableColumns.indexOf(b);
});
updateColumns(tmpColumns);
}
$scope.columns = columns;
$scope.availableColumns = availableColumns;
$scope.isSelected = function (column) {
return $scope.columns.indexOf(column) > -1;
};
$scope.toggleColumn = function (column) {
var columnIndex = $scope.columns.indexOf(column);
if (columnIndex === -1) {
addColumn(column);
} else {
$scope.columns.splice(columnIndex, 1);
}
};
$scope.reset = function () {
updateColumns(defaultColumns.slice());
};
$scope.close = function () {
$scope.showPanel = false;
};
function updateColumns(newColumns) {
$scope.columns = columns = newColumns;
}
}
};
});
I want to add "chargeAmount" to appear in the grid/table

you must have another columns somewhere, this columns
<div columns-panel columns="columns" show-panel="showColumnsPanel"></div>
try to add to your directive datas (the columns).
they are called here
scope: {
columns: '=',
showPanel: '='
},
and gave to the directive scope here
$scope.columns = columns;
so in your controller try to see what you have in columns

Related

AngularJS doesn't work with 'multiple' flag

I'm trying to filter some data from the select box. It works fine when I don't use the "multiple" flag. However, the idea here is to be able to select multiple environments and multiple applications and show it based the options I selected, but it is not working. I tried in many different ways, but I didn't find what I'm missing. Can someone help me here?
Here are the files which I'm using.
monitoring.html
<div ng-controller="monitoring" class="md-padding selectdemoOptionGroups" ng-cloak="" ng-app="monitor">
<div>
<h1 class="md-title">Monitoring</h1>
<div layout="row">
<md-input-container style="margin-right: 10px;">
<label>Segments</label>
<md-select ng-model="segment" >
<md-option ng-repeat="segment in segments" value="{{segment}}">{{segment}}</md-option>
</md-select>
</md-input-container>
<md-input-container>
<label>Environments</label>
<md-select ng-model="selectedEnvironments" multiple>
<md-optgroup label="environments">
<md-option ng-value="environment.name" ng-repeat="environment in environments | filter: {category: 'env' }">{{environment.name}}</md-option>
</md-optgroup>
</md-select>
</md-input-container>
<md-input-container>
<label>Applications</label>
<md-select ng-model="selectedApplications" multiple="">
<md-optgroup label="application">
<md-option ng-value="application.name" ng-repeat="application in applications | filter: {category: 'app' } ">{{application.name}}</md-option>
</md-optgroup>
</md-select>
</md-input-container>
<button ng-click="clear()" style="width: 55px; height: 50px;" id="iconTextButton">Clear</button>
<button style="width: 55px; height: 50px;" id="iconTextButton">Run</button>
</div>
<div class="md-card container-shadow" style="margin:15px">
<div class="card-header4">
Monitoring page1 for {{segment}}
</div>
<table id="grid422">
<colgroup>
<col style="width:830px" />
<col style="width:130px" />
<col style="width:130px" />
<col style="width:130px" />
</colgroup>
<thead align="left">
<tr>
<th >Application</th>
<th>Environment</th>
<th >StatusUP</th>
<th>StatusDown</th>
</tr>
</thead>
<tbody align="left" >
<tr ng-repeat="todo in todos | filter:segment | filter:selectedEnvironments | orderBy: 'application' ">
<td>{{todo.application}}</td>
<td>{{todo.environment}}</td>
<td>{{todo.statusUp}}</td>
<td>{{todo.statusDown}}<td>
</tr>
</tbody>
</table>
</div></div>
monitoring.js
(function (angular) {
angular
.module('monitor')
.controller('monitoring', function ($scope, $http) {
$scope.segments = [
"SegmentA",
"SegmentB",
"SegmentC"
];
$scope.selectedSegments = [];
$scope.printSelectedSegments = function printSelectedSegments() {
return this.selectedSegments.join('');
};
$scope.environments = [
{ category: 'env', name: 'ENV1' },
{ category: 'env', name: 'ENV2' },
{ category: 'env', name: 'ENV3' },
{ category: 'env', name: 'ENV4' }
];
$scope.selectedEnvironments = [];
$scope.printSelectedEnvironments = function printSelectedEnvironments() {
var numberOfEnvironments = this.selectedEnvironments.length;
if (numberOfEnvironments > 1) {
var needsOxfordComma = numberOfEnvironments > 2;
var lastEnvironmentConjunction = (needsOxfordComma ? ',' : '') + ' and ';
var lastEnvironment = lastEnvironmentConjunction +
this.selectedEnvironments[this.selectedEnvironments.length - 1];
return this.selectedEnvironments.slice(0, -1).join(', ') + lastEnvironment;
}
return this.selectedEnvironments.join('');
};
$scope.applications = [
{ category: 'app', name: 'App1' },
{ category: 'app', name: 'App2' },
{ category: 'app', name: 'App3' },
{ category: 'app', name: 'App4' }
];
$scope.selectedApplications = [];
$scope.printSelectedApplications = function printSelectedApplications() {
var numberOfApplications = this.selectedApplications.length;
if (numberOfApplications > 1) {
var needsOxfordComma = numberOfApplications > 2;
var lastApplicationConjunction = (needsOxfordComma ? ',' : '') + ' and ';
var lastApplication = lastApplicationConjunction +
this.selectedApplications[this.selectedApplications.length - 1];
return this.selectedApplications.slice(0, -1).join(', ') + lastApplication;
}
return this.selectedApplications.join('');
};
$scope.todos = [
{"segment":"SegmentA","application":"App1","environment":"ENV1","statusUp":57,"statusDown":"13"},{"segment":"SegmentB","application":"App2","environment":"ENV2","statusUp":12,"statusDown":"33"},{"segment":"SegmentC","application":"App3","environment":"ENV4","statusUp":357,"statusDown":"133"},{"segment":"SegmentA","application":"App1","environment":"ENV1","statusUp":57,"statusDown":"13"},{"segment":"SegmentB","application":"App2","environment":"ENV1","statusUp":12,"statusDown":"33"},{"segment":"SegmentC","application":"App3","environment":"ENV3","statusUp":333,"statusDown":"213"},{"segment":"SegmentB","application":"App1","environment":"ENV4","statusUp":357,"statusDown":"133"},{"segment":"SegmentC","application":"App2","environment":"ENV2","statusUp":57,"statusDown":"13"}
];
});
})(angular);
You can create custom function for filter
Updated code
<tbody align="left">
<tr ng-repeat="todo in todos | **filter: filterByGenres** | orderBy: 'application' ">
<td>{{todo.application}}</td>
<td>{{todo.environment}}</td>
<td>{{todo.statusUp}}</td>
<td>{{todo.statusDown}}
<td>
</tr>
angular controller side code
(function(angular) {
angular
.module('plunker', ['ngMaterial'])
.controller('monitoring', function($scope, $http) {
**$scope.filterByGenres = function(ele) {
var res = true
if ($scope.selectedEnvironments !== null && $scope.selectedEnvironments.length > 0) {
if ($scope.selectedEnvironments.indexOf(ele.environment) == -1) {
res = false;
}
}
if ($scope.selectedApplications !== null && $scope.selectedApplications.length > 0) {
if ($scope.selectedApplications.indexOf(ele.application) == -1) {
res = false;
}
}
return res;
}**
$scope.segments = [
"SegmentA",
"SegmentB",
"SegmentC"
];
...
Plunker here
Thanks
I just run your source on codepen.io and nothing output, try included md then everything ok. So, please try use .module('monitor', ['ngMaterial']) and test again.

AngularJS multiple filters

I want to filter my list's items using multiple filters.
This is how I fill my items list (Using Django):
<script type="text/javascript">
ngApp.controller('FilterInputCtrl', function ($scope, $rootScope) {
$scope.items1 = [];
{% for cross in crosses%}
$scope.items.push
({
id:{{ cross.id }},
name: '{{ cross.name }}',
comments: '{{ cross.comments }}',
aliases: '{{ cross.print_lines_aliases }}',
});
{% endfor %}
});
</script>
The one filter code is like this:
<li ng-repeat="cross in items | filter:myFilter">
which filters on all the item's fields (id, name, ... etc).
I want to filter the same way but using multiple filters that filter on all fields too. So the user may remeber segments from the name so he enters many segments from the name and then he maye remeber a segment from the comments and so on.
I found this way:
<li ng-repeat="cross in items | filter:{ name: filter1, lines: filter2, comments: filter3 }">
Which works fine, but each filter now is specific for one criterion.
The problem is that I don't know how will the user think when searching; maybe he will search for many segements of the comments!
I am looking for a way to apply many filters and each one filters according to every field without specifying a single field to each one.
Something looks like this maybe:
<li ng-repeat="cross in items | filter:{filter1, filter2, filter3}">
<li ng-repeat="cross in filteredItems = (items | filter:filter1 | filter:filter2 | filter:filter3)">
If you notice, I have created a new scope variable there called filteredItems. This makes it easy to check if there are any items left after filtering. You may wish to display a message such as "No items found" if !filteredItems.length.
E.g.
<div ng-hide="filteredItems.length" class="row">
<div class="col-xs-10 col-sm-11 col-md-11">No items found</div>
</div>
var app =angular.module('app', []);
app.controller('mainController', function($scope) {
// Data object
$scope.servers = [
{name:'ServerA', runlevel:'PAV', mode:'author', env:'intranet' },
{name:'Server7', runlevel:'PAV', mode:'publish', env:'intranet'},
{name:'Server2', runlevel:'PAV', mode:'publish', env:'intranet'},
{name:'ServerB', runlevel:'PAV', mode:'publish', env:'internet'},
{name:'ServerC', runlevel:'PAV', mode:'publish', env:'internet'},
{name:'Server1', runlevel:'UAT', mode:'author', env:'intranet'},
{name:'Server3', runlevel:'UAT', mode:'publish', env:'intranet'},
{name:'Server4', runlevel:'UAT', mode:'publish', env:'internet'},
{name:'ServerD', runlevel:'STA', mode:'author', env:'intranet'},
{name:'ServerE', runlevel:'STA', mode:'publish', env:'intranet'}
];
// Filter defaults
$scope.Filter = new Object();
$scope.Filter.runlevel = {'PAV':'PAV',
'UAT':'UAT',
'ST':'ST'
};
$scope.Filter.mode = {'author':'author',
'publish':'publish'
};
$scope.Filter.env = {'intranet':'intranet',
'internet':'internet'
};
// Default order
$scope.OrderFilter = 'runlevel';
});
// Global search filter
app.filter('searchFilter',function($filter) {
return function(items,searchfilter) {
var isSearchFilterEmpty = true;
angular.forEach(searchfilter, function(searchstring) {
if(searchstring !=null && searchstring !=""){
isSearchFilterEmpty= false;
}
});
if(!isSearchFilterEmpty){
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item, function(term,key) {
if(term != null && !isFound){
term = term.toString();
term = term.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
searchstring = searchstring.toLowerCase();
if(searchstring !="" && term.indexOf(searchstring) !=-1 && !isFound){
result.push(item);
isFound = true;
}
});
}
});
});
return result;
}else{
return items;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="mainController">
<h2>Runlevel</h2>
<label>PAV</label>
<input type="checkbox" ng-model="Filter.runlevel.PAV" ng-true-value="PAV" ng-false-value="!PAV" />
<label>UAT</label>
<input type="checkbox" ng-model="Filter.runlevel.UAT" ng-true-value="UAT" ng-false-value="!UAT" />
<label>ST</label>
<input type="checkbox" ng-model="Filter.runlevel.ST" ng-true-value="ST" ng-false-value="!ST"/>
<hr />
<h2>Runmode</h2>
<label>Author</label>
<input type="checkbox" ng-model="Filter.mode.author" ng-true-value="author" ng-false-value="!author" />
<label>Publish</label>
<input type="checkbox" ng-model="Filter.mode.publish" ng-true-value="publish" ng-false-value="!publish" />
<hr />
<h2>Environment</h2>
<label>Intranet</label>
<input type="checkbox" ng-model="Filter.env.intranet" ng-true-value="intranet" ng-false-value="!intranet" />
<label>Internet</label>
<input type="checkbox" ng-model="Filter.env.internet" ng-true-value="internet" ng-false-value="!internet" />
<hr />
<h2>Server list</h2>
<table width="100%" cellpadding="5">
<tr>
<th ng-click="OrderFilter='name'">Name</th>
<th ng-click="OrderFilter='runlevel'">Runlevel</th>
<th ng-click="OrderFilter='mode'">Runmode</th>
<th ng-click="OrderFilter='env'">Environment</th>
</tr>
<tr ng-repeat="server in servers | searchFilter:Filter.runlevel | searchFilter:Filter.mode | searchFilter:Filter.env | orderBy:OrderFilter">
<td>{{server.name}}</td>
<td>{{server.runlevel}}</td>
<td>{{server.mode}}</td>
<td>{{server.env}}</td>
</tr>
</table>
</div>
</div>

Getting AngularJS orderBy to sort both directions

I'm attempting to setup a clickable table column header that sort Ascending when first clicked, and Descending when clicked again. My ascending sort is working fine, but I'm not sure how to setup an expression within my OrderBy to sort Descending
My setup thus far:
Table html has something like
<th ng-click="sort('LastName')">Last Name</th>
My sort method looks like
scope.sort = function (columnName) {
if (angular.isDefined(scope.filter)) {
if (scope.filter.SortColumn == columnName) {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = scope.filters.SortDirection == "Asc" ? "Desc" : "Asc";
} else {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = "Asc";
}
}
};
And my ng-repeat looks as follows
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn">
How can I get the SortDirection to factor into the orderBy?
To simply reverse you'd change it to this:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : true">
It'd be best if you used a boolean in your controller, but this should work too:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : filter.SortDirection === 'Desc'">
And just for fun, here's how I do sorting with filtering in my tables.
Controller:
$scope.search = { query: ''};
$scope.sort = { field: 'defaultField', descending: true};
$scope.order = function(newValue) {
if(newValue === $scope.sort.field) {
$scope.sort.descending = !$scope.sort.descending;
} else {
$scope.sort = {field: newValue, descending: false};
}
};
$scope.filteredDocuments = function() {
var a = $filter('filter')($scope.documents, {$:$scope.search.query});
var b = $filter('orderBy')(a, $scope.sort.field, $scope.sort.descending);
return b;
};
A search box for filtering:
<input type="text" ng-model="search.query">
A column header:
<th nowrap>
<a href ng-click="order('size')">Size </a>
<i ng-show="sort.field === 'size' && !sort.descending" class="fa fa-sort-amount-asc"></i>
<i ng-show="sort.field === 'size' && sort.descending" class="fa fa-sort-amount-desc"></i>
</th>
The row binding:
<tr ng-repeat="d in filteredDocuments()" >
A simplified version of the above answer:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')" >Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:mySortOrder">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.sorts={};
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
if(x in $scope.sorts) {
$scope.sorts[x]=!$scope.sorts[x];
} else {
$scope.sorts[x]=false;
}
$scope.mySortOrder=$scope.sorts[x];
}
});
</script>
</body>
</html>

how to reset a filter by leaving it empty?

I have a filter on a list :
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a></td>
</tr>
</table>
I would like to clear searchFileName value when I click on a result.
This is openFolder function :
$scope.openFolder = function(name) {
$scope.searchFileName = null;
$http.jsonp($scope.server + '?open=' + encodeURIComponent($scope.buildTreePath()) + '&callback=JSON_CALLBACK').success(function(data){
$scope.folders = data;
});
}
}
I can't empty my filter field, it doesn't work... Where am I wrong ?
just use:
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
var app = angular.module('app', []);
app.controller('fCtrl', function($scope) {
$scope.folders = [
{
name: "Ala"
}, {
name: "Ata"
}, {
name: "Ara"
}, {
name: "Ama"
}
];
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a>
</td>
</tr>
</table>
</div>
</div>

angularJS: Filter JSON Data w.r.t Date Range

I am completely new to AngularJS. Here is my HTML code
<div ng-controller="DateRangeCtrl">
<div class="container">
<div class="form-horizontal">
<input type="text" datepicker-popup="MM-dd-yyyy" ng-model="dt1" is-open="opened1" max="maxFromDate" ng-change="setMinToDate()"/>
<button class="btn btn-sm" ng-click="open1($event)"><span class="glyphicon glyphicon-calendar"></span></button>
</div>
<div class="form-horizontal">
<input type="text" datepicker-popup="MM-dd-yyyy" ng-model="dt2" is-open="opened2" min="minToDate" max="maxToDate" ng-change="filterDateAdded()"/>
<button class="btn btn-sm" ng-click="open2($event)"><span class="glyphicon glyphicon-calendar"></span></button>
</div>
<p><strong>Selected From Date: </strong> {{dt1 | date:'mediumDate'}}</p>
<p><strong>Selected To Date: </strong> {{dt2 | date:'mediumDate'}}</p>
</div>
<hr />
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Date Added</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items | orderBy:mySortFunction ">
<td>{{item.ID}}</td>
<td>{{ parseDate(item.dateAdded) | date:'longDate'}}</td>
</tr>
</tbody>
</table>
</div>
The following is my angular code:
testApp.config(function (datepickerConfig, datepickerPopupConfig) {
datepickerConfig.showWeeks = false;
datepickerPopupConfig.showButtonBar = false;
});
testApp.controller('DateRangeCtrl', function($scope) {
$scope.items = [
{ID: "1", dateAdded: "01-04-2013"},
{ID: "2", dateAdded: "12-01-2013"},
{ID: "3", dateAdded: "12-31-2013"},
{ID: "4", dateAdded: "01-12-2014"},
{ID: "5", dateAdded: "03-04-2014"}
];
$scope.parseDate = function(input){
var parts = input.split('-');
var newParts = new Date(parts[2], parts[0]-1, parts[1]); // Note: months are 0-based
return newParts;
}
$scope.open1 = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened1 = true;
};
$scope.maxFromDate = new Date();
$scope.maxToDate = new Date();
$scope.setMinToDate = function (){
$scope.dt2 = null;
$scope.minToDate = $scope.dt1;
};
$scope.open2 = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened2 = true;
};
});
How can i filter rows based on selected dates? For e.g. if i select "01/01/2014" in the "From" datePicker then i should be able to see all the rows whose "Date Added" column has value more than "January 1, 2014". The output will be rows with ID: 4 and 5.
It should behave the literal equivalent way when the "To" datePicker is selected
Please help me out. i'm stuck!
Update:
HTML
<tr ng-repeat="item in items | filter:dateFilter ">
JS
$scope.dateFilter = function (item) {
return (item.dateAdded < $scope.dt2);
};
Am i doing anything wrong? It still doesn't work....
By some hit n trial method, i eventually got it right. The problem was the "item.dateAdded" string had to be converted to Date object. Solution is adding the following piece of code in the js file:
$scope.filterDateAdded = function (){
if($scope.dt1 != null)
{
$scope.dateFilter = function (item) {
return ($scope.parseDate(item.dateAdded) >= $scope.dt1 && $scope.parseDate(item.dateAdded) <= $scope.dt2);
};
}
};
Cheers!
Change your code like this
<input type="text" datepicker-popup="MM-dd-yyyy" ng-model="dt2" is-open="opened2" min="minToDate" max="maxToDate" ng-model="search" ng-change="filterDateAdded()"/>
<tr ng-repeat="item in items | filter:dateFilter">
$scope.filterDateAdded=function()
{
$scope.dateFilter = function () {
var result=[];
for(var i in $scope.item)
{ if($scope.item[i].dateAdded >$scope.search)
{
result.push($scope.item[i]);
}
}
return result;
};
}

Resources