On my website is a player that shows what song I'm currently listing to. However in order to update te song displayed, I had te refresh the page.
As for now, I want the code to check an external json file. It should check the songname and when a change is detected, it should update the player on the website.
Unfortunately, I'm hitting a roadblock here.
First I tried using the $interval
function, while this did work, it would refresh the <div>
like refreshing a page.
I tried the scope.$watch
function, but it doesn't seem to work. It looks like the $watch is only triggering once when the page is loading. This could be due to the scope not being a listener.
However, when I try to add the listener, I'd need to change the module since it's a directive...
angular.module('lastfm-nowplaying', [])
.directive('lastfmnowplaying', ['uiCreation', 'lastFmAPI', 'lastFmParser', '$http', function (uiCreation, lastFmAPI, lastFmParser, $http) {
var link = function (scope, element, attrs) {
$http({
method: 'GET',
url: 'https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=--NAME--&api_key=--API--&format=json&limit=1'
}).then(function (songdata) {
var currentsongs = songdata.data.recenttracks.track[0].name;
console.log(songdata);
console.log(currentsongs);
}, function (error) {
//oopsie
});
scope.$watch('currentsongs', function (value) {
load(value);
console.log("Change detected");
}, true);
var load = function () {
var latestTrack;
if (scope.config) {
if (scope.config.apiKey) {
lastFmAPI.getLatestScrobbles(scope.config).then(function (data) {
latestTrack = lastFmParser.getLatestTrack(data);
angular.element(element).addClass('lastfm-nowplaying');
uiCreation.create(element[0], scope.config.containerClass, latestTrack);
}, function (reason) {
//Last.fm failure
});
} else {
var latestTrack = {
title: scope.config.title,
artist: scope.config.artist,
largeImgUrl: scope.config.imgUrl,
xLargeImgUrl: scope.config.backgroundImgUrl,
}
angular.element(element).addClass('lastfm-nowplaying');
uiCreation.create(element[0], scope.config.containerClass, latestTrack);
}
}
}
};
return {
scope: {
config: '=config'
},
link: link
};
}])
HTML
<body ng-app="app" ng-controller="mainCtrl">
<div lastfmnowplaying config="lastFmConfig"></div>
</body>
So through the console I can call the json file and get the name of the song, but I can't update the player by using scope.$watch
, it only fires once(?)
I only know the basics of Angular and thus I'm not capable of solving this on my own anytime soon.