Reputation: 4422
I am building a website frontend using AngularJS 1.3.6. I would like to re-use some of my code as templates, and have it done as simple as possible. Preferably without using a controller.
I have a spotify play button link:
<iframe src="https://embed.spotify.com/?uri=spotify:track:4FAAYTHgGpjZZgdSwVsfen" width="300" height="80" frameborder="0" allowtransparency="true"></iframe>
The only thing changing is:
spotify:track:4FAAYTHgGpjZZgdSwVsfen
So I would like to make a custom directive in AngularJS which creates the iframe element when I write
<bb-spotify-play-button spotify-track-id="spotify:track:4FAAYTHgGpjZZgdSwVsfen"></bb-spotify-play-button>
I have tried this, but can't make it work, and I have trouble figuring the attrs object out: (I know - this code is just an attempt to get something out of attrs)
app.directive('bbSpotifyPlayBox', function() {
return {
'restrict': 'E',
'link': function(scope, element, attrs) {
element.text(attrs.getAttribute('spotifyTrackId'))
}
}
Also, I would like to avoid using a controller for this, as I want to use the directive in as simple a way as possible.
Any suggestions?
Here a plunker to play with: Plunker
Maybe it's also my habits from PHP and Laravel, where I would do something like:
@include('spotify-play-box', ['spotify-track-id' => 'xxxx'])
Upvotes: 0
Views: 170
Reputation: 193261
The main thing you should do is whitelist resource in order Angulars $sce
module agree to render iframe:
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'https://embed.spotify.com/**'
]);
});
then you can do something like this (note using ngSrc
directive):
app.directive('bbSpotifyPlayBox', function() {
return {
restrict: 'E',
scope: {
spotifyTrackId: '@'
},
template: '<iframe ng-src="{{spotifyTrack}}" width="300" height="80" frameborder="0" allowtransparency="true"></iframe>',
link: function(scope) {
scope.spotifyTrack = "https://embed.spotify.com/?uri=" + scope.spotifyTrackId;
}
}
});
Upvotes: 2