AngularJs same model for main window and iframe wi

2019-09-01 09:11发布

问题:

I am trying to open a new iframe window upon clicking some link on the main window. However, I would like to use the same model i.e if the data changes in main window, it should be reflected in iframe and vice versa. Main window UI will have couple fields whereas iFrame window will have all the fields.

I am pretty new to angujar world, is it doable? If yes, any suggestions?

回答1:

The concept of multiple templates on an angularjs page is trivial using the ngInclude directive.

And the ngCompile example shows a draggable div.

It should be easy enough to place an ng-include inside the draggable element. You can also use the same controller for the whole page, including the ngInclude, removing the need for sharing data through a service or factory.

Edit:

I have created a simple JS Fiddle showing a single template. As you can see the input fields are in the main page. Then a div with an ng-include directive loads an inline template (in practice these will be full separate html pages).

As the included template doesn't have a separate controller (which is possible, and commonly used), it is within the parent controller's scope. Thus the template has access to the name.first and name.last variables.

You will learn more about these by going through the angularjs tutorial



回答2:

No you cannot. The new iFrame is running in a different context. Also there is security restrictions between the iFrame and the parent if the are from different domains.

What you can do is to implement a messaging system between the parent and the iframe using html5 postmessage. You can watch for changes on your scope in the main window notify the child of the changes and update the scope of the child.