Filter JSON data by date Angularjs - angularjs

I'm trying to filter the following JSON, so that I only load the up and coming fixtures, in other words all fixtures from the current time onwards. But nothing loads, do I have something wrong, maybe the format of the date, not sure.
JSON
http://www.football-data.org/teams/354/fixtures/?callback=JSON_CALLBACK
FILTER
angular.module('PremierLeagueApp', [])
.filter('upComingFixtures', function() {
return function (fixtures) {
var filtered_list = [];
for (var i = 0; i < fixtures.length; i++) {
var currentTime = new Date().getTime();
var fixtureDate = new Date(fixtures[i].date).getTime();
if (currentTime <= fixtureDate) {
filtered_list.push(fixtures[i]);
}
}
return filtered_list;
}
});
CONTROLLER
.controller('fixturesController', function($scope, $routeParams, footballdataAPIservice) {
$scope.id = $routeParams.id;
$scope.fixtures = [];
footballdataAPIservice.getFixtures($scope.id).success(function (response) {
$scope.fixtures = response;
});
});
HTML
<tr ng-repeat="fixture in fixtures.fixtures | upComingFixtures">
<td>{{$index + 1}}</td>
<td>{{teamName(fixture.awayTeam)}}</td>
</tr>

I believe your filter should accept a value and then return true/false to either include that value or not. Something like this
<tr ng-repeat="fixture in fixtures.fixtures | upComingFixtures(fixture)">
$scope.upComingFixtures = function(fixture) {
if(fixture time > current time) {
return true; // include this
} else {
return false; // Don't include this
}
}

Sorry, I forgot to declare the filter in the app.js:
angular.module('PremierLeagueApp', [
'PremierLeagueApp.services',
'PremierLeagueApp.controllers',
'PremierLeagueApp.filters',
'ngRoute','ngAnimate'
]).
so all's fine with the code above :) Thanks in any case.

Related

How to find an array object according to given information?

I have an array in AngularJS controller like this:
$scope.persons = [{name:'Joey', age:'27'},{name:'Lucy', age:'22'}]
I have got a name 'Lucy', how can I get the age of the name in the controller (not in HTML)?
I've created a plunk here that outlines a single result, with just the age, as well as multiple results.
This could also be implemented within a filter, which is documented on the Angular site here: https://docs.angularjs.org/api/ng/filter/filter
https://plnkr.co/edit/OFRMzpQrZfTOnaFyJP7Z?p=info
angular.module('plnk',[]).controller('plnkCtrl', function($scope){
// Note, I added a second Joey here to test the multiple function.
// For output, check the browser console.
$scope.persons = [{name:'Joey', age:'27'},{name:'Joey', age:'28'},{name:'Lucy', age:'22'}]
console.log('Single -> ', getAgeSingle('Lucy'));
console.log('Multiple ->',getAgeMultiple('Joey'));
function getAgeMultiple(personLookup) {
var results = [];
angular.forEach($scope.persons,function(person){
if (person.name === personLookup) {
results.push(person);
// or results.push(person.age) for age only
}
});
return results;
}
function getAgeSingle(personLookup) {
var result = '';
angular.forEach($scope.persons,function(person){
if (person.name === personLookup && !result) {
result = person.age;
}
});
return result;
}
});
Just loop over the array and check, like this:
function getAge(name)
{
for (var i = 0; i < $scope.persons.length; i++)
{
var person = $scope.persons[i];
if (person.name === name)
{
return parseInt(person.age, 10);
}
}
return undefined;
}
This has a couple caveats -- if you have dupes you'll only get the first one and it runs in linear time. If you control the data source it'd be better to use a JS object/hashmap/dictionary/whatever you want to call it.
If you wanted to loop through the scope:
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}]
function getAge(name) {
angular.forEach($scope.persons, function (value, index) {
if (value.name === name) {
return parseInt(value.age, 10);
}
});
return undefined;
}
The HTML way:
<div ng-app="myApp" ng-controller="MainCtrl">
<table>
<tr ng-repeat="person in persons">
<td>Name: {{person.name}} Age: {{person.age}}</td>
</tr>
</table>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.persons = [{name:'Joey', age:'27'}, {name:'Lucy', age:'22'}];
});

Filter Change the color of the word in the sentence angularjs

I want to change the color of the word in the sentence How can i do that?
Controller code:
app.controller("myController",function($scope){
$scope.phrase="This is a bad phrase";
});
app.filter('censor', function(){
return function(input){
var cWords = ['bad', 'evil', 'dark'];
var out = input;
for(var i=0; i<cWords.length;i++){
out = out.replace(cWords[i], <span class="blue"></span>);
}
return out;
};
})
My view:
{{phrase | censor}}
First of all, if you want to bind html in your filter, you need to use ngSanitize and binding with the directive: ng-bind-html instead of {{ }}, like this:
<p ng-bind-html="ctrl.phrase | censor"></p>
In your js file you need to check if the phrase contain any of the words you want to filter out, then update the phrase.
angular
.module('app', ['ngSanitize'])
.controller('MainCtrl', function() {
var ctrl = this;
ctrl.phrase = 'This is a bad phrase';
})
.filter('censor', function() {
return function(input) {
var cWords = ['bad', 'evil', 'dark'];
var splitPhrase = input.split(' ');
var out = splitPhrase.reduce(function(acc, curr) {
if (cWords.indexOf(curr) > -1) {
acc.push('<span class="blue">' + curr + '</span>');
} else {
acc.push(curr);
}
return acc;
}, []);
return out.join(' ');
}
});
You can find an example here: http://jsbin.com/koxekoq/edit?html,js,output

AngularJS custom filter don't receive data

I have a problem with a new filter which don't receive the data:
here my error log:
Controller Code:
angular.module('reklaApp')
.controller('MainCtrl', function ($scope, $http, Reklas, Modal) {
$scope.newRekla = {};
Reklas.getAll()
.success(function(data) {
$scope.reklas = data;
});
Filter Code:
angular.module('reklaApp')
.filter('dateFilter', function () {
return function (items) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
filtered.push(item);
}
return filtered;
};
});
HTML Code:
<tr ng-repeat="rekla in reklas | dateFilter">
<td>{{rekla.dt | date: 'dd.MM.yyyy'}}</td>
<td>{{rekla.order}}</td>
<td>{{rekla.personal}}</td>
<td>{{rekla.department}}</td>
<td>{{rekla.xyz}}</td>
<td>{{rekla.desc | limitTo: '50'}}</td>
<td>{{rekla.costs}}</td>
I think the "item" variable dont receive the data from the ng-repeat!?
It's because you didn't create it to begin with on your $scope. So since your getAll function takes some time the filter doesn't have the data. You can fix this two ways:
By first initializing the variable:
angular.module('reklaApp')
.controller('MainCtrl', function ($scope, $http, Reklas, Modal) {
$scope.newRekla = {};
$scope.reklas = [];
Reklas.getAll()
.success(function(data) {
$scope.reklas = data;
});
Or by updating your filter:
angular.module('reklaApp')
.filter('dateFilter', function () {
return function (items) {
if(!angular.isArray(items)){ return items }
var filtered = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
filtered.push(item);
}
return filtered;
};
});

Get a list of contacts using cordova?

Sorry for my bad English.
How to get a list of contacts by using the Cordova angularjs?
Thanks in advance. Kind regards.
I don't know how your cordova-app is built up and but you could do it this way( take into consideration that I've not tested this):
Code:
First request contacts of your device by using the condact-plugin of cordova:
(same link as provided earlier: http://docs.phonegap.com/en/edge/cordova_contacts_contacts.md.html)
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// when using the plugin:
// you can put it within your angularjs-controllers
// where it will be executed and onSuccess-callback is called.
var options = new ContactFindOptions();
options.filter = "";
options.multiple=true;
var fields = ["displayName", "name"];
navigator.contacts.find(fields, onSuccess, onError, options);
}
// within this function you have to assign contacts to a model
function onSuccess(contacts) {
$scope.contacts = contacts;
}
function onError(contactError) {
alert('onError!');
}
HTML:
Iterate over each contact-object of your contacts-collection assigned within onSuccess-function:
<div ng-repeat="contact in contacts">{{contact.name.formatted}}</div>
Tutorial: http://www.quora.com/What-is-the-way-to-get-all-contacts-using-PhoneGap-on-Android
Putting the plugin into a angularjs-controller could look like this:
angular.module('aModule', [])
.controller('contactCtrl', ['$scope', function($scope) {
var options = new ContactFindOptions();
options.multiple = true;
options.filter = "";
var fields = ["displayName", "name"];
navigator.contacts.find(fields,
function(contacts){
var arr = [];
for (var i = 0; i < contacts.length; i++)
{
arr.push({name: contacts[i].name.formatted})
}
$scope.contacts = arr;
},
function(error){ console.log(error); },
options
);
}])
HTML:
<div ng-app="aModule" ng-controller="contactCtrl">
<div ng-repeat="contact in contacts">{{contact.name}}</div>
</div>

Load data to dropdown in angularjs

I am new to this angular js.
In my code a dropdown control has been loaded with some items, i know this list should be loaded from a xml file.
I want to know where/how it is been coded to load the data. Check this code and help me...
<select size="10" ng-model="model.addSelection" ng-options="a.name for a in availableList | availableList | propertyFilter:model.availableFilter" class="listBoxStyle" wat-focus/>
angular.module('readbackSelectModule', [])
.filter('availableList', [
function () {
return function (input) {
if (!angular.isArray(input)) return input;
var out = [];
for (var i = 0; i < input.length; i++) {
if (input[i].visible == true)
out.push(input[i]);
}
return out;
}
}
])
.filter('plotList', [
function () {
return function (input) {
if (!angular.isArray(input)) return input;
var out = [];
for (var i = 0; i < input.length; i++) {
if (input[i].visible == false)
out.push(input[i]);
}
return out;
}
}
])
.controller('readbackSelectCtrl', ['$scope', '$modalInstance', 'generalDataService', 'keyService', 'propertyFilterFilter', 'availableListFilter', 'plotListFilter', 'plotPanelService',
function ($scope, $modalInstance, generalDataService, keyService, propertyFilterFilter, availableListFilter, plotListFilter, plotPanelService) {
var CANCEL_MESSAGE = 'cancel';
var GET_DATA_MESSAGE = 'getdata';
var REQUEST_PROPERTY_LIST_MESSAGE = 'requestplotdata';
var SUBSCRIBE = 'plotsubscribe';
var UNSUBSCRIBE = 'plotunsubscribe';
var STREAM_TYPE = '4';
$scope.model = {};
$scope.model.addSelection;
$scope.model.removeSelection;
$scope.model.availableFilter;
// List of properties
$scope.availableList = [];
};
Use Angular's $http service.
You can do it in your readbackSelectCtrl, like this:
...
$scope.model = {};
$scope.model.addSelection;
$scope.model.removeSelection;
$scope.model.availableFilter;
$http.get(/** insert XML file URL here **/)
.success(function(data) {
// process the data and extract the XML elements you want
$scope.availableList = xmlExtractedArray;
})
.error(function(err) {
// handle error
});
Check this plunker for a working demo.

Resources