Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing iframe contents in AngularJS

I am writing an application which is part Angular and part jQuery. I am separating them by loading the jQuery content in an iFrame.

Upon a certain event (say, upon a ng-click), I need to refresh the iFrame. My Controller contains the following code:

$scope.refreshIframe = function() { //refresh the iFrame with id "anIframe" };

and the iFrame is:

<iframe id="anIframe" src="myUrl"></iframe>
like image 288
Amarsh Avatar asked Sep 10 '13 11:09

Amarsh


2 Answers

As Paulo Scardine said, the right way to do it would be through a directive cause you shouldn't use controllers to manipulate DOM.

Something like this one could do :

.directive('refreshable', [function () {
    return {
        restrict: 'A',
        scope: {
            refresh: "=refreshable"
        },
        link: function (scope, element, attr) {
            var refreshMe = function () {
                element.attr('src', element.attr('src'));
            };

            scope.$watch('refresh', function (newVal, oldVal) {
                if (scope.refresh) {
                    scope.refresh = false;
                    refreshMe();
                }
            });
        }
    };
}])

Which could then be used like :

<iframe refreshable="tab.refresh"></iframe>

And :

$scope.refreshIframe = function(){
    $scope.tab.refresh = true;
}
like image 94
Florian F. Avatar answered Nov 03 '22 01:11

Florian F.


Another hack-ish solution: if you don't want to create a directive but want to stick to the good practices of not manipulating the DOM in controller. Keep the url in an array and use ng-repeat to render the iFrame: View:

<iframe ng-repeat="url in vm.url" ng-src="{{url}}" />

Controller:

vm.url = ['http://google.com'];

So, every time you set the value of the vm.url, angular will re-render the iFrame.

like image 7
Dan Mihai Patrascu Avatar answered Nov 03 '22 01:11

Dan Mihai Patrascu