Search code examples
angularjsiframerefresh

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>

Solution

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