I have an iframe and it's contents should be bound to a controller function. I tried
<iframe ng-bind-html-unsafe="selectedMessage.content()"></iframe>
but unfortunately it doesn't seem to work. The correct way to write contents to an iframe would be to gain access to the iframe DOM element and invoke ifrmElem.contentDocument.write(s).
How can I accomplish this?
You can achieve this by setting a watcher on a property, and then manually updating the iframe when required.
Example below uses cross-browser iframe content selection.
See jsFiddle: http://jsfiddle.net/uyLNY/2/
$scope.$watch('data.content', function(oldValue, newValue) {
var ifrm = $element.find('iframe')[0];
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(newValue);
ifrm.document.close();
});
However worth noting I am unsure of the performance of this, if you were to be writing a large amount of content.
Here's a plnkr: http://plnkr.co/edit/LG7p1AG7yhVKyLXgMX4Q?p=preview
Javascript
$scope.content= "";
$scope.fillFrame = function(id) {
document.getElementById(id).contentDocument.write($scope.content);
};
HTML
<strong>Enter some html</strong>
<br/>
<textarea ng-model="content"></textarea>
<button ng-click="fillFrame('frame')">Fill iFrame</button>