0

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'])

1 Answer 1

2

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;
        }
    }
});

Demo: http://plnkr.co/edit/N17ZqD0hAkIODatgBYOi?p=preview

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. So the problem was both getting the scope right, and also whitelisting the URI?
Yes, but the main problem was making allowed resource for iframe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.