AngularJS Experiment: Get NPR stations near you
by Joe Steinbring
HTML
<body ng-app="NPRApp" ng-controller="NPRCtrl">
<h1>Nearby Public Radio Stations</h1>
<ul>
<li ng-repeat="marketCity in marketCities">
<h2>{{marketCity.label}}</h2>
<ul>
<li ng-repeat="station in marketCity.stations">
<div class="StationInfo">
<div class="label">{{station.orgDisplayName}}</div>
<div class="logo" ng-show="station.image.content">
<!-- Remember to use ng-src instead of src for images -->
<img ng-src="{{station.image.content}}" alt="{{station.orgDisplayName}}">
</div>
<div class="player"> <a href="{{station.url.content}}">Listen Live</a>
</div>
<div style="clear:both;"></div>
</div>
</li>
</ul>
</li>
</ul>
</body>
CSS
/* Styles go here */
.StationInfo .label {
font-weight: bold;
}
.StationInfo .logo {
float:left;
height: 30px;
margin-right: 40px;
margin-bottom: 12px;
vertical-align: middle;
}
.StationInfo .player {
float:left;
height: 30px;
margin-bottom: 15px;
vertical-align: middle;
}
.StationInfo {
margin: 2px;
padding: 6px;
width:50%;
}
ul {
list-style-type:none;
}
JavaScript
// The module
var NPRApp = angular.module('NPRApp', []);
// The controller
NPRApp.controller('NPRCtrl', ['$scope', '$http', function ($scope, $http) {
// Define the Zip Code
zipcode = 53201;
// Define the JSON feed
jsonFeed = "https://query.yahooapis.com/v1/public/yql?q=SELECT%20id%2C%20image%2C%20marketCity%2C%20orgDisplayName%2C%20url.type%2C%20url.typeId%2C%20url.content%20%20FROM%20npr.stations%20WHERE%20zip%3D'" + zipcode + "'%20and%20url.typeId%20%3D%20'10'%3B&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
// Actually fetch the data
$http.get(jsonFeed).success(function (data) {
// Define the unique market cities
$scope.marketCities = [];
for (var i = 0; i < data.query.results.station.length; i++) {
// if it isn't already there, add it
if (i !== 0 && data.query.results.station[i].marketCity !== data.query.results.station[i - 1].marketCity) {
$scope.marketCities.push({
label: data.query.results.station[i].marketCity,
stations: [data.query.results.station[i]]
});
} else if (i == 0) {
$scope.marketCities.push({
label: data.query.results.station[i].marketCity,
stations: [data.query.results.station[i]]
});
} else if (data.query.results.station[i].id !== data.query.results.station[i - 1].id) {
// is the market already there? well, just add the station then.
$scope.marketCities[$scope.marketCities.length - 1].stations.push(data.query.results.station[i]);
}
}
});
}]);