Here I have created AngularJS directive for setting and getting scroll position of an IFrame. Two way binding was applied here. Observe below markup.
Note : This directive wont work for cross domain iframes sources (For security reasons, browsers won't allow this)

Markup

Observe ng-iframe-scroll attribute. This is the main directive. ng-iframe-scroll-x, ng-iframe-scroll-y are supporting  directives. ng-iframe-scroll-x will bind to X-axix scroll positions. ng-iframe-scroll-y will bind to Y-axix scroll positions
<iframe src="myFrame.html" ng-iframe-scroll ng-iframe-scroll-x="xval" ng-iframe-scroll-y="yval"></iframe>

Script

Observe below code for directive
angular.module('myApp', []).controller('MyController', [ '$scope', function($scope) {
    $scope.iFrameScroll = {x:10,y:1000};
}]).directive('ngIframeScroll', function(){
     return {
           restrict : "A",
           scope : {sx:'=ngIframeScrollX', sy:'=ngIframeScrollY'},
           link : function(scope, element, attrs) {
              var y;
              var x;

              element.bind("load", function(event) {
                  this.contentWindow.onscroll = function (e) {
                     x = this.pageXOffset;
                     y = this.pageYOffset;
                     setValues();
                  };
                  scrollIt();
                 });
              
              scope.$watch('sy', function(val){
                  y = val;
                  scrollIt();
              });
              
              scope.$watch('sx', function(val){
                  x = val;
                  scrollIt();
              });
              
              function scrollIt() {
                  var doc = (element[0].contentWindow || element.contentDocument);
                  doc.scrollTo(x, y);
              }
              
              function setValues() {
                  scope.sx = x;
                  scope.sy = y;  
                  scope.$apply();
              }
           }
        };
});

0 comments:

Blogroll

Popular Posts