SiYan Xie SiYan Xie - 6 months ago 123
AngularJS Question

I can't bind string to html element in angular js

I am sorry, i am new on ionic(angularjs). I have tried to bind from string, the string is containing youtub video url.

<iframe width="280" height="150" src="//www.youtube.com/embed/UAHEQnOtzuw?list=UUj4nCgtjKJppK_IZeY8TUJg" frameborder="0" allowfullscreen></iframe>


In controller

$scope.videoElement.str = $scope.item.restData.videos[0].link;


In html

<div ng-bind-html="videoElement.str"></div>


but i can't see nothing. :(

Here is screenshot. http://screencast.com/t/Fgct1sdnOon

How can i fix this issue? Thank you for an advance.

Answer

A link would not append to a div unless you make use of $sce. Keep using the iframe and embed the url as string as:

<iframe width="280" height="150" ng-src="{{videoElement.str}}" frameborder="0" allowfullscreen></iframe>

If you still need to bind the iframe to a div then this is probably how you can achieve it:

Controller:

$scope.frame= '<iframe src="' + $scope.videoElement.str + '"></iframe>';

View:

<div ng-bind-html="frame| safeHtml">

Where safeHtml is a filter directive to safely bind the html and makes use of $sce - Documentation

Include this in the app:

app.filter('safeHtml', function ($sce) {
    return function (val) {
        return $sce.trustAsHtml(val);
    };
});

UPDATE:

If $scope.videoElement.str is the Iframe link, then the below code would suffice as:

<div ng-bind-html="videoElement.str | safeHtml">

Also, add the safeHtml directive as mentioned above in the app.js or after the end of controller.