So, I have two single page applications, these two apps both contain a list of items, in Application A
we have List A
, and in Application B
we have List B
.
an item in List A
can be the parent for items in List B
, one to many relations.
If a user clicks an item in App A
, he gets the option to view related items
, this will open up App B
in a separate window (new tab), and filter List B
to only show related items to the clicked item in App A
.
This means I have to open a new window, and run a function when that window is ready, and pass the ID
of the clicked item in order to filter my list.
$scope.openNewWindow = function(id){
var popup = window.open('newPageUrl');
// check to see when opened page is ready
var readyStateCheckInterval = setInterval(function() {
if (popup.document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
// function on App B
popup.functionToRunWhenReady(id);
}
}, 50);
};
The function, functionToRunWhenReady()
is a javascript function, and has to run the actual function to filter my list, which is a $scope
function, the reason is that I can't access the $scope
function from my other application
function functionToRunWhenReady(id) {
angular.element(document).ready(function () {
var scope = angular.element($('#myAppDiv')).scope();
scope.$apply(function() {
// scope function to filter the list
scope.setFilter(id);
});
});
}
As you can see here I check if document
is ready, access the scope
by doing var scope = angular.element($('#myAppDiv')).scope();
and then run my setFilter(id)
function
This works, but I can't believe that this is the best way to go about this.
tl;dr How do I open a new window, then run a $scope function on the new application, in a way that is not bad practice?
Edit: I see people are suggesting $routeparams
, but I don't really know how that works, or if it works in my apps (they are both single page apps), so further explanation of that would be great
Send ID as a GET parameter to Application B. You can then access it directly in controller without any delays using $routeParams.
In Application A, you don't need any special code to open a window. Just a target="blank"
link in your markup.
<a href="http://applicationB_url/{{itemA.id}}/items" target="blank">{{itemA.name}}</a>
And then in Application B, depending on your router, use $stateParams
(for ui router
) or $routeParams
to access the id in your controller.
If you want to run a function on startup, just check for the existence of the id in your Application B controller. Something like:
if($stateParams.id) {
// do something
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With