Here is a working code. It is for demo purpose to show how you can work with multiple windows. Instead hovering, it needs you to click on a search link to create or set focus to the new window. Also it demonstrates the action of the window-closing by removing the corresponding search result itself.
What we are going to do is to have an array of references to the the opened windows in our controller. You should create your DOM search results with appropriate attributes and populate this array as you insert them to the document.
Here is what the array should look like after loading your search results.
$scope.winRef = [ {id: 'user1', w: 0, show: true},
{id: 'user2', w: 0, show: true},
{id: 'user3', w: 0, show: true}];
The array can record the window handler (w), user id and the show status. The show status is bound to the DOM element through ng-show
.
Here is the DOM search results:
<a href="#" ng-click="openWindow(0)" id="user1" ng-show="winRef[0].show">User1</a> <br>
<a href="#" ng-click="openWindow(1)" id="user1" ng-show="winRef[1].show">User2</a> <br>
<a href="#" ng-click="openWindow(2)" id="user1" ng-show="winRef[2].show">User3</a> <br>
You cans see that when the user clicks on a link it calls the openWindow()
function. This function checks through the array if a window is already opened for this user. It opens one if yes or set the focus through w
if not. Here is your openWindow
function:
$scope.openWindow = function(userIdx) {
if ($scope.winRef[userIdx].w === 0) {
$scope.winRef[userIdx].w = $window.open();
//Write something in the new page
$scope.winRef[userIdx].w.document.write($scope.winRef[userIdx].id);
//Set the unload event for your new window.
$scope.winRef[userIdx].w.onbeforeunload = function() {
//Note that we create a closure here. Also note the
//applicaiton of the $apply here.
$scope.$apply($scope.winRef[userIdx].show = false);
};
}
else
$scope.winRef[userIdx].w.focus();
};
And finally you can see that I have bound the unbeforeunload
event of the new window with a function. This function sets the show
property of the appropriate element false
to hide your DOM search result. Here is the function:
$scope.removeSearchResult = function(userIdx) {
$scope.winRef[userIdx].show = false;
};
This code works perfectly if you put them inside a controller. Also read my comments on the code to note few things I have highlighted.
This is a rough idea of how you should solve your problem. This can extend greatly by loading an html file to the new window and making the controller interact with it through onload
event of the new window. Please play with it and learn your methods.