× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Angularjs: call other scope which in iframe

Feb 12, 2015
<p>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: </p> <p>*You don’t need the parent to have reference to angularJS library…</p> <p><strong>Calling to child iFrame from parent</strong></p> <p>1.Get child iFrame element from the parent (<a href="http://stackoverflow.com/questions/251420/invoking-javascript-code-in-an-iframe-from-the-parent-page">link to answer</a>): </p> <blockquote> <p>document.getElementById("myIframe").contentWindow</p> </blockquote> <p>2.Access the scope of the element: </p> <blockquote> <p>document.getElementById("myIframe").contentWindow.angular.element("#someDiv").scope()</p> </blockquote> <p>3.Call the scope’s function or property: </p> <blockquote> <p>document.getElementById("myIframe").contentWindow.angular.element("#someDiv").scope().someAngularFunction(data);</p> </blockquote> <p>4.Call $scope.$apply after running the logic of the function/updating the property (<a href="http://stackoverflow.com/questions/10490570/call-angular-js-from-legacy-code/10508731#10508731">link to Mishko’s answer</a>): </p> <blockquote> <p>$scope.$apply(function () { });</p> </blockquote> <ul> <li>Another solution is to share the scope between the iFrames, but then you need angular in both sides: (<a href="http://stackoverflow.com/questions/19125910/is-it-possible-to-update-angularjs-expressions-inside-of-an-iframe/19126316#19126316">link to answer and example</a>)</li> </ul> <p><strong>Calling parent from child iFrame</strong></p> <ol> <li>Calling the parent function: </li> </ol> <blockquote> <p>parent.someChildsFunction();</p> </blockquote> <p>Will update also on how to do it cross domain if it is necessary..</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/18437594/Angularjs:%20call%20other%20scope%20which%20in%20iframe/21733164">Stack Overflow</a>.</p>
comments powered by Disqus