Angularjs: call other scope which in iframe

前端 未结 4 2116
清酒与你
清酒与你 2020-11-27 13:44

In my test, given 2 document, A and B. In A document, there is an iframe, the iframe source is B document. My question is how to modify B document certain scope of variable?

相关标签:
4条回答
  • 2020-11-27 14:25

    This one is quite simple and works for me:

    in the controller code of iframe page:

    $window.parent.window.updatedata($scope.data);
    

    in the parent page controller code:

    window.updatedata = function (data) {
     $scope.$apply(function () {
         $scope.data = data
       }
     }
    
    0 讨论(0)
  • 2020-11-27 14:44

    To access and communicate in two directions (parent to iFrame, iFrame to parent), in case they are both in the same domain, with access to the angular scope, try following those steps:

    *You don’t need the parent to have reference to angularJS library…

    Calling to child iFrame from parent

    1.Get child iFrame element from the parent (link to answer):

    document.getElementById("myIframe").contentWindow

    2.Access the scope of the element:

    document.getElementById("myIframe").contentWindow.angular.element("#someDiv").scope()

    3.Call the scope’s function or property:

    document.getElementById("myIframe").contentWindow.angular.element("#someDiv").scope().someAngularFunction(data);

    4.Call $scope.$apply after running the logic of the function/updating the property (link to Mishko’s answer):

    $scope.$apply(function () { });

    • Another solution is to share the scope between the iFrames, but then you need angular in both sides: (link to answer and example)

    Calling parent from child iFrame

    1. Calling the parent function:

    parent.someChildsFunction();

    Will update also on how to do it cross domain if it is necessary..

    0 讨论(0)
  • 2020-11-27 14:45

    You should be able to get parent scope from iFrame:

    var parentScope = $window.parent.angular.element($window.frameElement).scope();
    

    Then you can call parent method or change parent variable( but remember to call parentScope.$apply to sync the changes)

    Tested on Angular 1.3.4

    0 讨论(0)
  • 2020-11-27 14:48

    The best way in my mind to communicate with the iframe is using window.top. If you want your iframe to get your parent's scope, you can set window.scopeToShare = $scope; within your controller and it becomes accessible for the iframe page at window.top.scopeToShare.

    If you want your parent to get the iframe scope, you can use

    window.receiveScope = function(scope) {
      scope.$on('event', function() {
        /* Treat the event */
      }
    };
    

    and within the iframe controller call window.top.giveRootScope($rootScope);

    WARNING: If you are using this controller multiple times, make sure to use an additional ID to identify which scope you want.

    0 讨论(0)
提交回复
热议问题