Shivam Vahia Shivam Vahia - 6 months ago 33
Javascript Question

AngularJS GET Request with Parameter

I'm working on a project wherein Analytics from a WordPress Site need to be requested in an App via AngularJS GET Function. I want to filter out data from the JSON API. Can someone please help me with the Code?

JSON: http://happyshappy.13llama.com/wp-json/llama/v1/stats

I need to display the "label" , "data" as Monday, Tuesday, Wednesday, Thursday...

Here's what I've done until now:

<html ng-app="countryApp">

<head>
<meta charset="utf-8">
<title>Angular.js JSON Fetching Example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

<script>

var countryApp = angular.module('countryApp', []);

countryApp.controller('CountryCtrl', function ($scope, $http){

$http.get('http://happyshappy.13llama.com/wp-json/llama/v1/stats').success(function(data) {

$scope.countries = data;

});

});

</script>

Answer

Given the dates are provided in the labels array, you could transform the data arrays with something like this

$http.get(url).then(function(response) {
    var visitDates = response.data.visits.labels.map(function(dateString) {
        return new Date(dateString);
    });

    $scope.visits = response.data.visits.datasets;

    angular.forEach($scope.visits, function(dataSet) {
        dataSet.data = dataSet.data.map(function(count, i) {
            return {
                date: visitDates[i],
                count: count
            };
        });
    });
})

Then, each data entry will have a date that you can pass through Angular's date filter.

<div ng-repeat="dataSet in visits">
    <h4>{{dataSet.label}}</h4>
    <ul>
        <li ng-repeat="datum in dataSet.data">{{datum.date | date: 'EEEE'}} is {{datum.count | number}}</li>
    </ul>
</div>

If you're not comfortable with using strings like "May 28, 2016" in the Date constructor, you could always use something like moment.js to parse them.

Plunker demo ~ http://plnkr.co/edit/eXu6T8Zvr1fDjlGArFEY?p=preview