I have a custom directive for soundcloud that requires a soundcloud url. The soundcloud URL is retrieved from the database through the $ http service, however, a div is loaded for the soundcloud attribute and the soundcloud url value is required before it is determined.
I mean the code, https://github.com/jxnblk/plangular/blob/master/src/plangular.js * I have not developed this
This is my HTML code:
<div plangular="{{soundcloud}}"> <button ng-click="playPause()">Play/Pause</button> <progress ng-value="currentTime / duration || 0"> {{ currentTime / duration || 0 }} </progress> </div>
And this is the Angular Code:
displaySong.controller('song', ['$scope', '$http', 'fetchSong', function($scope, $http, fetchSong) { $scope.songID $scope.songName; //Controller properties $scope.songPromise; //The song promise for fetching $scope.init = function(songID, userID) { $scope.songID = songID; $scope.userID = userID; $scope.songPromise = $http({ method: "post", url: fetchSong, data: { song_id: $scope.songID }, headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function(successResponse) { console.log('Successfully fetched song'); console.log(successResponse); var song = successResponse.data; $scope.songID = song.song_id; $scope.songName = song.song_name; $scope.songType = song.song_type; $scope.songEmbed = song.song_embed; $scope.soundcloud = song.song_embed; }, function(errorResponse) { console.log('Error fetching'); $scope.songID = null; }); }; }]);
I know this is an asynchronous character issue, because when I add this line at the beginning of my song controller:
$scope.soundcloud = "https://soundcloud.com/jshigley/shine";
It works great. I also noticed that when I spam the play / pause button that appears from the directive, I get several console errors "HTTP 404 Not Found", which makes me believe that trying to find the track undefined URL
Since this is a div directive, not a function call, I cannot use promises, for example, chaining a then to my scope $ scope.songPromise. I was thinking of putting it in the controller, and the controller should do something like $ timeout within 5 seconds, but I don't think this delays the execution of the DOM.
The soundcloud url eventually loads, but it remains undefined in the eyes of the plangular directive (in fact, I came across many of these problems with poor loading time of the area and directives). Any Angular wizards wanting to teach me how to tame the asynchronous nature of AngularJS?