Create filter based on date Angularjs - angularjs

I am loading in this JSON into my angular app:
http://www.football-data.org/teams/354/fixtures/?callback=JSON_CALLBACK
I would like to only load fixtures that are up-coming i.e only show the fixture details that are later than the present time.
I have a controller as so:
.controller('fixturesController', function($scope, $routeParams, footballdataAPIservice) {
$scope.id = $routeParams.id;
$scope.fixtures = [];
$scope.pageClass = 'page-fixtures';
footballdataAPIservice.getFixtures($scope.id).success(function (response) {
$scope.fixtures = response;
});
});
HTML
<tr ng-repeat="fixture in fixtures.fixtures">
<td>{{$index + 1}}</td>
<td>{{teamName(fixture.awayTeam)}}</td>
Not sure how to do this, especially with the format I have for the time and day: "2015-03-14T15:00:00Z"

Your dates are already in the correct format for a date conversion, so you only need to create a filter yourself.
I'd just create a custom filter like the one I put down here. Adjust it to your needs.
angular.module('yourApp')
.filter('greaterThan', function() {
return function (actualDate, comparisonDate) {
return Date(actualDate) > Date(comparisonDate);
};
});
Then your HTML could look like this:
<tr ng-repeat="fixture in fixtures.fixtures | greaterThan:fixture.date:'2015-03-14T15:00:00Z'">
...
</tr>

Related

Unable to bind Json Data with Table Header using AngularJS

Im getting data in this format from api, but when i try binding it to table using angularjs it is creating empty space instead of values. Im also getting more then one table from some Api's please explain who to bind different datatables in different tables too. thanks
{"Table":
[{
"SchoolId":1,
"schoolname":"Microsoft",
"SCHOOLCODE":"29911583",
"WEBSITE":"JLR",
"USEREMAIL":"faucibus#aliquamiaculislacus.org",
"PHONE":"841-9331",
"ADDRESS1":"682-5760 Felis Street",
"ISACTIVE":0,
"PLANTYPE":3
}]
}
Angular Controller
SMSApp.factory('GetStudentService', function ($http) {
studobj = {};
studobj.getAll = function () {
var stud=[];
stud = $http({ method: 'Get', url: 'http://localhost:58545/api/Student?Studentid=1' }).
then(function (response) {
return response.data;
});
return stud;
};
return studobj;
});
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result;
console.log(result);
});
});
HTML Code
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
WHAT I GET
Change in your Angular Controller :
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
/********************* Changed Here ********************/
$scope.school = JSON.parse(result._body); // Or only JSON.parse(result)
$scope.school = $scope.school.table;
});
});
And your HTML Code :
<tbody ng-controller="studentController">
<tr ng-repeat="schools in school track by $index">
<td>{{schools.SchoolId}}</td>
<td>{{schools.schoolname}}</td>
<td>{{schools.SCHOOLCODE}}</td>
<td>{{schools.WEBSITE}}</td>
<td>{{schools.USEREMAIL}}</td>
</tr>
</tbody>
Naming the data school is confusing. Do instead:
GetStudentService.getAll().then(function (data) {
$scope.tableObj = data;
console.log(data);
});
<tbody ng-controller="studentController">
<tr ng-repeat="school in tableObj.Table track by school.SchoolId">
<td>{{school.SchoolId}}</td>
<td>{{school.schoolname}}</td>
<td>{{school.SCHOOLCODE}}</td>
<td>{{school.WEBSITE}}</td>
<td>{{school.USEREMAIL}}</td>
</tr>
</tbody>
From the Docs:
Best Practice: If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance, e.g. item in items track by item.id. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance.
— AngularJS ng-repeat API Reference
Just replace your result with result.Table in your controller because if you properly see your response it is inside "Table" named array. Try this you should be able to see your records
SMSApp.controller('studentController', function ($scope, GetStudentService) {
$scope.msg = "Welcome from Controller";
GetStudentService.getAll().then(function (result) {
$scope.school = result.Table;
console.log(result);
});
});
Note: I have replaced your API call in the jsfiddle link with the response mentioned in the question.
JSFiddle Link : http://jsfiddle.net/zu8q7go6/9/

get values to edit in an other page with Angular

I have values that I want to edit in an other page
<tr ng-repeat="facilitator in listFacilitators" ng-click="showDetails(facilitator);goToFacilitatorP()">
<td>{{facilitator.username}}</td>
<td><li><ul>{{facilitator.cwsessionsAnime}}</ul></li></td>
<td><li><ul>{{facilitator.profilFollow}}</ul></li></td>
</tr>
when I click on I'm supposing to be redirected in another page to show the details and edit them , so I tried to do this in the controller:
$scope.showDetails= function(facilitator){
$scope.selectedFac= facilitator;
}
and in the second page, I do this:
<tr>
<td> {{selectedFac.username}}</td>
<td> {{selectedFac.lastname}}</td>
<td> {{selectedFac.firstname}}</td>
<td> {{selectedFac.title}}</td>
</tr>
it works in the same page but not when I'm redirected, can you help me please?
UPDATE:
I do this but I still haven't data in the seconde page:
1- In the first controller for the 1 page I declared:
profilCtrl.controller('ProfilCtrl', [ '$scope','$location', 'profilService', 'facilitatorPService', function($scope,$location, profilService, facilitatorPService) {
/* ---- appel a facilitator Service ---- */
var facilitator = '';// What ever this is set to in the first place
facilitatorPService.facilitator = facilitator;
2- In my 2nd controller (for the second in where I want to show the details) , I have declared:
facilitatorPCtrl.controller('facilitatorPCtrl', [ '$scope','$rootScope','$cookieStore','$location','membreService','facilitatorPService','userService',function($scope,$rootScope,$cookieStore,$location, membreService,facilitatorPService, userService) {
facilitatorPservice.editFacil= function($scope){
$scope.showDetails = function(){
$scope.selectedFac = facilitatorPService.facilitator;
}
};
3- Ans in my service facilitatorPService I have this:
facilitatorPService.factory('facilitatorPService', [ '$resource','$http', function($resource,$http) {
var service = {
getAllFacilitators : function($scope){
return $resource('/gari-web/services/facilitators/AllFacilitators', {}, {
query : {
method : 'GET', isArray:true,
}}
});
},
editFacil: function($scope){
var self= this;
self.facilitator={};
}};
return service;
} ]);
4- in My html page I put this:
<td>{{selectedFac.username}}</td>
Can someone please tell me what I did wrong, I don't find the mistake
Controllers are 'flushed' when you change views. To keep data from a view to another, store your data within a Service.
UPDATE
.service('FacilitatorService', [
function() {
var self = this;
self.facilitator = {};
}
])
Then in your controllers, inject yourself the service you just created.
.controller('FirstController', ['FacilitatorService',
function(FacilitatorService) {
var facilitator = '';// What ever this is set to in the first place
FacilitatorService.facilitator = facilitator;
}
])
And in your second controller
.controller('SecondController', ['FacilitatorService', '$scope',
function(FacilitatorService, $scope) {
$scope.showDetails = function(){
$scope.selectedFac = FacilitatorService.facilitator;
}
}
])
Like this, your FacilitatorService.facilitator data will be accesible in all your controllers that use FacilitatorService
I recommend using ui router, this resolve two problems, the view change and the data share.
Read more about router ui
doc http://angular-ui.github.io/ui-router/site/#/api/ui.router
The current state
$stateProvider
.state('current', {
url: "/curent",
templateUrl: 'current.html',
controller: 'currentCtrl'
})
Then you can choose how change the view and share the data, the first is the controller, the second is html. Only use one
From current controller (option 1)
$scope.showDetails= function(facilitator){
$state.go('togo', {myCurrentdata: facilitator}) ;
}
From current html (option2)
<tr ng-repeat="facilitator in listFacilitators" ui-sref="togo({myCurrentdata : facilitator})">
<td>{{facilitator.username}}</td>
<td><li><ul>{{facilitator.cwsessionsAnime}}</ul></li></td>
<td><li><ul>{{facilitator.profilFollow}}</ul></li></td>
</tr>
The state that you want to go
$stateProvider
.state('togo', {
url: "/togo",
templateUrl: 'togo.html',
controller: 'togoCtrl'
param: {myCurrentdata: null}
})
To go controller
if($stateParams.myCurrentdata){
$scope.selectedFac = $stateParams.myCurrentdata
}

How to echo JSON array as Smart Table data with Angluarjs

I'm pretty new to Angular, and trying to build a table using Smart Table based on data I'm fetching from a REST api. I can build the table fine with manually entered data, but when I try to insert a JSON array of data from the server the resulting table is empty.
Currently I have the following set up:
dataFactory.js - calls the API and gets a JSON response:
app.factory('dataFactory', ['$http', function($http) {
var urlBase = 'http://myurl.com/api';
var dataFactory = {};
dataFactory.getOrders = function() {
return $http.get(urlBase + '/orders');
};
return dataFactory;
}]);
My view is fairly basic and looks like this using to the Smart Table extension:
<div ng-controller="MainController">
<table st-table="ordersTable" class="table table-striped">
<thead>
<tr>
<th st-sort="createdBy">Name</th>
<th st-sort="id">ID</th>
<th st-sort="state">State</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in ordersTable">
<td>{{row.createdBy}}</td>
<td>{{row.id}}</td>
<td>{{row.state}}</td>
</tr>
</tbody>
</table>
</div>
And my MainController.js processes and stores the data, and builds the table:
app.controller('MainController', ['$scope', 'dataFactory', function($scope, dataFactory) {
$scope.status;
$scope.orders;
getOrders();
function getOrders() {
dataFactory.getOrders()
.success(function(ord) {
$scope.orders = ord;
})
.error(function(error) {
$scope.status = 'Unable to load order data: ' + error.message;
});
}
$scope.ordersTable = [
// If I build the data manually the table builds using the following 3 lines
//{createdBy: 'Laurent', id: '56433', state: 'Open')},
//{createdBy: 'Blandine', id: '34367', state: 'Open')},
//{createdBy: 'Francoise', id: '34566', state: 'Closed'}
//... however I actually want the data to come from the JSON array returned by my factory like this:
$scope.orders
];
}]);
What am I doing wrong? How can I get my data to show up in the table?
In the success callback you are updating $scope.orders and not $scope.orderTable. By the way use promise function then instead of success and error callback (extract from angularjs doc):
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

ASP.Net WEB API AND ANGULAR Not outputting one column vs another

I was able to set up a asp.net web api and scaffolding to my sql server database. The return of the records from sql server appears to be JSON. The model has a few tables linked to each other by foreign keys and only has 2 records right now. Comp_Id = 1 and 2. The results to my local api looks like this:
[{"ASSOC_INC_OFF":[{"OFFICERINVOLVEDs":[],"AIO_ID":1,"COMP_ID":1,"OFCNUM":1,"LINK_TYPE":null}],"CRITICALINCIDENTs":[{"CIType":"Physical Force resulting in Death or Serious Bodily Injury","CINotice":null,"CIMonitorRolledOut1":null,"CIDAMonitored":null,"CIOIMQuestions":null,"CICharged":null,"CIMonitor1":null,"CIMonitor2":null,"CINotes":null,"CIOfcCharges":null,"CIOutcome":null,"COMP_ID":1,"RolledOut_DT":null,"CI_ID":1,"CINotice_DT":"2016-01-07T00:00:00","CIOIMAllegNotes":null,"CIMonitorRolledOut2":null,"CIMonitorRolledOut3":null,"CIMonitorRolledOut4":null,"CIMonitorRolledOut5":null,"CIMonitorRolledOut6":null,"CIMonitorRolledOut7":null}],"COMP_ID":1,"FileNum":"case1","Received_DT":"2016-01-21T00:00:00","Completed_DT":null,"OIMIntake_DT":null,"Status":null,"Occurred_DT":null,"ComplaintType":null,"Source":"Chiefs Office","Precinct":"District 2","AddrCity":null,"AddrState":null,"AddrZip":null,"CaseSummary":null,"IABNotified_DT":null,"ClosureLetSent_DT":null,"CaseType":null,"OIMOutcome":null,"InitialFinding":null,"ClosedFindings":null,"OIMRecFinding":null,"timestamp":null,"Department":"DSD","Address":null,"DeclineReason":null,"Filenum2":null,"Filenum3":null,"OIMDiscRev_DT":null,"OIMInvRev_DT":null,"OIMInvRoute_DT":null,"OIMDiscRoute_DT":null,"CRORoute_DT":null},{"ASSOC_INC_OFF":[],"CRITICALINCIDENTs":[{"CIType":"Officer/Deputy-Involved Shooting","CINotice":null,"CIMonitorRolledOut1":null,"CIDAMonitored":null,"CIOIMQuestions":null,"CICharged":null,"CIMonitor1":null,"CIMonitor2":null,"CINotes":null,"CIOfcCharges":null,"CIOutcome":null,"COMP_ID":2,"RolledOut_DT":null,"CI_ID":2,"CINotice_DT":null,"CIOIMAllegNotes":null,"CIMonitorRolledOut2":null,"CIMonitorRolledOut3":null,"CIMonitorRolledOut4":null,"CIMonitorRolledOut5":null,"CIMonitorRolledOut6":null,"CIMonitorRolledOut7":null}],"COMP_ID":2,"FileNum":"cw1","Received_DT":"2016-01-03T00:00:00","Completed_DT":null,"OIMIntake_DT":null,"Status":"Active","Occurred_DT":null,"ComplaintType":null,"Source":"Citizen Walk-in","Precinct":"District 7","AddrCity":null,"AddrState":null,"AddrZip":null,"CaseSummary":null,"IABNotified_DT":null,"ClosureLetSent_DT":null,"CaseType":"District-Bureau","OIMOutcome":"Satisfactory","InitialFinding":"Formal","ClosedFindings":null,"OIMRecFinding":"Decline","timestamp":null,"Department":"DSD","Address":null,"DeclineReason":"Body Worn Camera","Filenum2":null,"Filenum3":null,"OIMDiscRev_DT":null,"OIMInvRev_DT":null,"OIMInvRoute_DT":null,"OIMDiscRoute_DT":null,"CRORoute_DT":null}]
I am able to bind COMP_ID to my view but when I add in CIType, nothings appears.
console.log($scope.complaints) returns:
My Controller looks like this:
app.controller('UpdateController', function ($scope, ComplaintService) {
getCities();
function getCities() {
ComplaintService.getCities()
.success(function (complaints) {
$scope.complaints = complaints;
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
}
});
My service looks like this:
app.factory('ComplaintService', ['$http', function ($http){
var urlBase = 'http://localhost:63942/api';
var ComplaintService = {};
ComplaintService.getCities = function () {
return $http.get(urlBase+ '/complaints');
};
return ComplaintService;
}]);
and my index looks like this:
<div class="row">
<div class="col-md-3" ng-controller="UpdateController">
<table class="table">
<tr>
<th>Id</th>
<th>CI TYPE</th>
<tr ng-repeat="a in complaints">
<td>{{a.COMP_ID}}</td>
<td>{{a.CIType }}</td>
</table>
</div>
I am certainly confused about why I can render out only COMPID but not the rest of this api contents as it is all listed under localhost:###/api/complaints.
var someResultArray = [];
$scope.complaints.forEach(function(elem){
//basically checks if this exists in the object to avoid undefined issues
if(elem.ASSOC_INF_OFF){
elem.ASSOC_INF_OFF.forEach(function(assoc){
//do something with each assoc, ex: push it to another array
someResultArray.push(assoc);
});
}
});
an object in javascript can be treated by dotting yourself down, or you can also address its content by index, even though its an object. So you could write elem["ASSOC_INF_OFF"], and it would still work.

AngularJS: accessing/printing a property of a related collection

I've defined two collections in Angular:
app.controller('MainCtrl', function($scope, PieceService, TeamService) {
PieceService.query(function(data){
$scope.pieces = data;
});
TeamService.query(function(data){
$scope.teams = data;
});
});
pieces is a collection that looks like this: [{name:'Petra',team_id:2},{name:'Jan',team_id:3}]
team is a collection that looks like this: [{name:'TeamA',id:2},{name:'Team',id:3}]
In the template I am iterating over the pieces collection:
<tr data-ng-repeat="piece in pieces">
How can I print the teamname of each piece?
I've tried creating a filter that does this, but as I don't see how I can access the scope in a filter I'm without luck so far.
Not sure if this is the sexiest angular way to do it, but I would create a function inside your controller to do the lookup. I also decided to cache the team_id to name lookup, but I realize it's not really necessary for a 2x2 search.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.pieces = [{name:'Petra',team_id:2},{name:'Jan',team_id:3}];
$scope.teams = [{name:'TeamA',id:2},{name:'TeamB',id:3}];
var idcache = {};
$scope.getTeam = function(id) {
if(idcache[id]) {
return idcache[id];
}
//cache this
$scope.teams.forEach(function(team) {
idcache[team.id] = team.name;
});
return idcache[id];
}
});
I've created a plunkr with the example code.
http://plnkr.co/edit/DsafIfMfARurNeVcl9Qd?p=preview
Use team ID as an object key, like this:
$scope.teamLookup = {}
// do this in the query callback
angular.forEach($scope.teams, function(val, key){
$scope.teamLookup[val.id] = val.name
});
Then, your markup can look like this:
<tr data-ng-repeat="piece in pieces">
<td>{{teamLookup[piece.team_id]}}</td>
<td>{{piece.name}}</td>
</tr>

Resources