AngularJS - Open link in new tab when conditionally routing via controller - javascript

In my app, I have two types of profile for organisations. When a user click on a profile name, I first need to check whether I have a premium profile for that organisation, and if so, route the user in that direction. If there is no premium profile, the user is sent to the standard profile.
I'm doing this using ng-click, which send id and a resource (in this case, organisation) parameters to a controller, where the conditions are evaluated and then the user is routed in the correct direction. All of this works correctly when a user clicks as normal.
However, when a user tries to open the link in a new tab, by right clicking and selecting that option, the new tab opens with the url of the current page. So the ng-click and controller has not fired or evaluated the request before opening the new tab.
How can I change by code so that Angular processes the ng-click request before opening the new tab? Or more broadly, how can I allow my users to open one of these links in a new tab so that they are not just displayed the page they are currently on?
HTML
<div ng-controller="ProfileRouter">
<div ng-repeat="org in orgs | orderBy:'org.name'">
{{ org.name }}
</div>
</div>
Inside ProfileRouter controller
$scope.profileCheck = function (id, resource) {
$http({method: 'GET', url:'/IdCheck', params:{'id': id})
.success(function(data) {
var count = data.hits.found;
if (count) {
var hash = data.hits.hit[0].id;
}
if (resource == 'organisation') {
theResource = 'universities';
page = 'overview';
}
if (count == 1) {
window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
}
if (count == 0) {
window.location.href = "/" + resource + "/" + id;
}
})
.error(function(data) {
$scope.data = data || "Can't get resource";
});
}

I know this is an old question. But I found out a solution to this & posting it here might help someone else.
First of all I have created a custom directive for right click:
module.directive('tabRightClick',['$parse', function($parse) {
return function(scope, element, attrs) {
var fn = $parse(attrs.tabRightClick);
element.bind('contextmenu', function(event) {
scope.$apply(function() {
// event.preventDefault();
fn(scope, {$event:event});
});
});
};
}]);
Then applied this directive as an attribute in the HTML file and call the same method that is being called on ng-click:
<div ng-controller="ProfileRouter">
<div ng-repeat="org in orgs | orderBy:'org.name'">
{{ org.name }}
</div>
</div>
Here locationPath is a $scope bound variable, which we need to implement in the controller.
Its value should be updated in the profileCheck function based on the various conditions.
$scope.profileCheck = function (id, resource) {
$http({method: 'GET', url:'/IdCheck', params:{'id': id})
.success(function(data) {
var count = data.hits.found;
if (count) {
var hash = data.hits.hit[0].id;
}
if (resource == 'organisation') {
theResource = 'universities';
page = 'overview';
}
if (count == 1) {
window.location.href = "/" + theResource + "/profile/" + hash + "/" + page;
$scope.locationPath = "/" + theResource + "/profile/" + hash + "/" + page;
}
if (count == 0) {
window.location.href = "/" + resource + "/" + id;
$scope.locationPath = "/" + resource + "/" + id;
}
})
.error(function(data) {
$scope.data = data || "Can't get resource";
});
}
Hope it's helpful.

Related

My code has a simple issue that i cant figure out

I am setting up a link for my web page to take me to another site.
Ive tried everything i know how to do . my knowledge is limited though. basically when you visit https://beatsbycayde.com/roster/ it should take you to
"https://braytech.org/2/{destinyId}/{characterId}/legend"
for some reason it doesnt And I cannot figure out why any help would be greatly appreciated it it instead takes you to
https://braytech.org/2/{destinyId}/fstats/legend
I know that i have fstats in there iam trying to us it as an object and call it in the href
// get list of members and populate roster table
var roster = [];
$.when($.ajax({
url: "https://www.bungie.net/platform/GroupV2/699392/Members/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(json) {
if (json.ErrorStatus === 'Success') {
roster = json.Response.results;
console.log('Exalted member list:', roster);
} else {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}
}).error(function(json) {
alert('Uh oh, looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(json);
}), $.ajax({
url: 'https://www.bungie.net/platform/destiny2/2/profile/4611686018429000034/?components=200',
headers: {
'X-API-Key': "47b810e692d64237911c2cbe0d433cfe"
}
}).success(function(res) {
console.log('PS4 stats:', res);
})).then(function() {
listMembers(roster);
});
function listMembers(rsp) {
var list = $('.memberList-list'),
on = 0,
sortMembers = function(method) {
// sort by date joined
if (method = joined) {
list.find('.member').sort(function(a, b) {
return ($(b).data('joined')) < ($(a).data('joined')) ? 1 : -1;
}).appendTo(list);
} else if (method = username) {
list.find('.member').sort(function(a, b) {
return ($(b).data('username')) < ($(a).data('username')) ? 1 : -1;
}).appendTo(list);
}
list.find('.member.online').prependTo(list);
};
for (var i = 0; i < rsp.length; i++) {
var profile = rsp[i].bungieNetUserInfo,
member = $('<a></a>');
// tally up online members
if (rsp[i].isOnline) {
on++
}
// check for valid profile
// some users don't have Bungie profiles somehow and it breaks function
if (typeof profile != 'undefined') {
// store response data in semantic variables
var name = rsp[i].destinyUserInfo.displayName,
joinDate = rsp[i].joinDate,
joined = joinDate.substring(0, joinDate.indexOf('T')),
online = rsp[i].isOnline,
icon = profile.iconPath,
memberId = profile.membershipId,
memberType = rsp[i].destinyUserInfo.membershipType,
destinyId = rsp[i].destinyUserInfo.membershipId,
rank = rsp[i].memberType;
// configure D OM node and add to page
$('#destiny-Id').text(destinyId);
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/" + destinyId + "/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
}
}).done(function(json) {});
$(function() {
$.ajax({
url: "https://www.bungie.net/Platform/Destiny/2/Account/4611686018429000034/",
headers: {
"X-API-Key": "47b810e692d64237911c2cbe0d433cfe"
},
success: function(data) {
// Gambit stats
var fstats = data.Response.data.characters[0].characterBase.characterId;
// Populate stats
// pvp
$('#player-f-stats').text(fstats);
},
error: function(data) {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log('Error loading player stats:', data);
}
});
});
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
'title': 'See player profile for ' + name,
'data-joined': joined.replace(/-/g, ''),
'data-username': name,
'data-online': 'false',
'data-searchable': name,
}).html('<div class="j-col j-col-1 member-icon"><img src="https://bungie.net/' + icon + '"></div>' + '<div class="j-col j-col-3 member-name"><h3>' + name + '</h3></div>' + '<div class="j-col j-col-3 member-joined" data-label="Joined">' + joined.replace(/-/g, '/') + '</div>' + '<div class="j-col j-col-3 member-status" data-label="Status"><span class="member-online" id="status-' + memberId + '">' + online + '</span></div>' + '<div class="j-col j-col-3 member-button"><a class="button outline gold full-width">' + 'View Stats' + '</a></div>' + '<div class="j-col j-col-3 member-button"> + In Depth Stats' + '</a></div>').appendTo(list);
// indicate online/offline status
if (String(online) === 'true') {
$('#status-' + memberId).text('Online').addClass('online').closest('.member').attr('data-online', true).addClass('online');
} else {
$('#status-' + memberId).text('Offline').removeClass('online');
}
sortMembers(joined); // sort members by join date
}
}
}
You have nested links. That breaks your HTML and prevents the href you want to be used.
Here you create the wrapper of each member. Which is a link.
member.attr({
'class': 'j-row vertical-center-row member',
'href': '/player/?bungieId=' + memberId + '&destinyId=' + destinyId + '&joined=' + joined + '&rank=' + rank,
...
And then you append another link inside of it here:
... In Depth Stats' ...
So I would suggest that you change the structure of your member element. Maybe place the top link in the position of the View Stats button and change that button to a <a> tag. But then as a consensus the whole member element won't be clickable, only the links.
Good luck!

How to make API request from HTML select tags?

I need help with this scenario, getting all data from multiple select tag
and use those data to send an API request.
I have these three select tags, and one button to send a request to a news API.
The user needs to select a value from those select tags to set data like "source" and "category".
Example: "https://xxxxxxxxxxxx.org/v2/top-headlines?source='+ source +' + '&category='+ cat +'&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Not sure if this the efficient way.
Below is my js code.
//global variables
var apiUrl = 'https://xxxxxxxxxxxxxxxxxx',
apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxx',
displayRequest = document.querySelector('.displayRequestData'),
requestBtn = document.querySelector('#runApi'), //Btn to display data
newsOpt = document.querySelector('#news-selection'), //news select tag
catOpt = document.querySelector('#news-category'); //category select tag
requestBtn.addEventListener('click', newsRequest); //onclick
function sourceSelected() { //news option
var source = newsOpt !== null ? newsOpt.options[newsOpt.selectedIndex].value : 'the-next-web';
var cat = catOpt !== null ? catOpt.options[catOpt.selectedIndex].value : 'general';
return newsRequest(source, cat);
}
function newsRequest(source, cat) {
axios.get(apiUrl + 'top-headlines?sources=' + source + '&language=' + cat + '&apiKey=' + apiKey)
.then(function (response) {
var reStringify = JSON.stringify(response);
var rejson = JSON.parse(reStringify);
if (rejson.data.status == 'ok'){
console.log(rejson.data.articles[1].source.name);
//console.log(requestBtn);
}
})
.catch(function (error) {
console.log(error);
});
}
By the way, i got this error
VM7472:1 GET https://xxxxxxxxxxxxxxxxxxxxxxxx/v2/top-headlines?sources=[object%20MouseEvent]&language=undefined&apiKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxx 400 (Bad Request)
When you add the event listener to call newsRequest via onClick, the first and only parameter that will be sent to that function is the event object. Therefore, the parameters of source and cat are not passed to newsRequest when they click on the button. (This is why your resulting URL has the [object MouseEvent] in it)
Instead, you might want to call your sourceSelected function in the onClick event which is fetching the current field values and then calling the newsRequest function.
I play around with my code, it's working now.
Note: The news API I'm using not allowing me to mix some data like country, source and langauge. So I try things that only allowed for free account and it works.
requestBtn.addEventListener('click', sourceSelected); //onchange
function sourceSelected() { //news option
var source = newsOpt !== null ? newsOpt.options[newsOpt.selectedIndex].value : 'en';
var cat = catOpt !== null ? catOpt.options[catOpt.selectedIndex].value : 'general';
return newsRequest(source, cat);
} //end of sourceSelected
function newsRequest(source, cat) {
axios.get(apiUrl + 'top-headlines?country=' + source + '&category=' + cat + '&apiKey=' + apiKey)
.then(function (response) {
var reStringify = JSON.stringify(response);
var rejson = JSON.parse(reStringify);
if (rejson.data.status == 'ok') {
console.log(rejson.data.articles[1].source.name);
//console.log(requestBtn);
}
})
.catch(function (error) {
console.log(error);
});
}//newsRequest

What is wrong with my foursquare api call?

The live example is here
http://kenziejoy.github.io/frontend-nanodegree-map/
I'm trying to pull data about locations that I have hard coded in an array - either by their foursquare id (didn't seem to be working) or their lat and lng. (client ID and secret are variables I just haven't shown them here)
I don't need any other functionality than just pulling data from their database to display on a map so I thought it would fall under the userless access but it is giving me an error that the request are bad because I don't have the proper authentication.
Thanks in advance
From the foursquare site
"Userless access
Some of our endpoints that don’t pertain to specific user information, such as venues search are enabled for userless access (meaning you don’t need to have a user auth your app for access). To make a userless request, specify your consumer key's Client ID and Secret instead of an auth token in the request URL.
https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=YYYYMMDD
To see what level of permissions each endpoint needs, check out the filters at the top of our endpoints page."
/**********FourSquare***************/
$.ajax({
url:'https://api.foursquare.com/v2/venues/search',
dataType: 'json',
data: 'limit=1' +
'&ll='+ placeItem.lat() +','+ placeItem.lng() +
'&?client_id='+ CLIENT_ID +
'&client_secret='+ CLIENT_SECRET +
'&v=20140806' +
'&m=foursquare',
async: true,
success: function (data) {
var result = data.response.venue;
var contact = result.hasOwnProperty('contact') ? result.contact : '';
if (contact.hasOwnProperty('formattedPhone')) {
placeItem.phone(contact.formattedPhone || '');
}
var location = result.hasOwnProperty('location') ? result.location : '';
if (location.hasOwnProperty('address')) {
placeItem.address(location.address || '');
}
var bestPhoto = result.hasOwnProperty('bestPhoto') ? result.bestPhoto : '';
if (bestPhoto.hasOwnProperty('prefix')) {
placeItem.photoPrefix(bestPhoto.prefix || '');
}
if (bestPhoto.hasOwnProperty('suffix')) {
placeItem.photoSuffix(bestPhoto.suffix || '');
}
var description = result.hasOwnProperty('description') ? result.description : '';
placeItem.description(description || '');
var rating = result.hasOwnProperty('rating') ? result.rating : '';
placeItem.rating(rating || 'none');
var url = result.hasOwnProperty('url') ? result.url : '';
placeItem.url(url || '');
placeItem.canonicalUrl(result.canonicalUrl);
// Infowindow code is in the success function so that the error message
// Content of the infowindow
var contentString = '<div id="iWindow"><h4>' + placeItem.name() + '</h4><div id="pic"><img src="' +
placeItem.photoPrefix() + '110x110' + placeItem.photoSuffix() +
'" alt="Image Location"></div><p>Information from Foursquare:</p><p>' +
placeItem.phone() + '</p><p>' + placeItem.address() + '</p><p>' +
placeItem.description() + '</p><p>Rating: ' + placeItem.rating() +
'</p><p><a href=' + placeItem.url() + '>' + placeItem.url() +
'</a></p><p><a target="_blank" href=' + placeItem.canonicalUrl() +
'>Foursquare Page</a></p><p><a target="_blank" href=https://www.google.com/maps/dir/Current+Location/' +
placeItem.lat() + ',' + placeItem.lng() + '>Directions</a></p></div>';
// Add infowindows
google.maps.event.addListener(placeItem.marker, 'click', function () {
infowindow.open(map, this);
// Bounce animation
placeItem.marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
placeItem.marker.setAnimation(null);
}, 800);
infowindow.setContent(contentString);
});
},
// Alert the user on error.
error: function (e) {
infowindow.setContent('<h5>Foursquare data is unavailable.</h5>');
document.getElementById("error").innerHTML = "<h4>Foursquare data is unavailable. Please try refreshing.</h4>";
}
});
I took a look at the live example URL and you were getting a lot of bad request errors in the JavaScript console in Chrome.
Looking at these, you had a bad URL, you were using:
https://api.foursquare.com/v2/venues/search?limit=1&ll=45.5589522,-122.6517163&?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&v=20140806&m=foursquare
The problem seems to be that you have:
&?client_id
which makes the URL invalid.
Changing this to
&client_id
fixes this and I then see data coming back from Foursquare.

AngularJS and ASP.Net WebAPI Social Login on a Mobile Browser

I am following this article on Social Logins with AngularJS and ASP.Net WebAPI (which is quite good):
ASP.NET Web API 2 external logins with Facebook and Google in AngularJS app
Pretty much, the code works fine when you are running the social login through a desktop browser (i.e. Chrome, FF, IE, Edge). The social login opens in a new window (not tab) and you are able to use either your Google or Facebook account and once your are logged in through any of them, you are redirected to the callback page (authComplete.html), and the callback page has a JS file defined (authComplete.js) that would close the window and execute a command on the parent window.
the angularJS controller which calls the external login url and opens a popup window (not tab) on desktop browsers:
loginController.js
'use strict';
app.controller('loginController', ['$scope', '$location', 'authService', 'ngAuthSettings', function ($scope, $location, authService, ngAuthSettings) {
$scope.loginData = {
userName: "",
password: "",
useRefreshTokens: false
};
$scope.message = "";
$scope.login = function () {
authService.login($scope.loginData).then(function (response) {
$location.path('/orders');
},
function (err) {
$scope.message = err.error_description;
});
};
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.$windowScope = $scope;
var oauthWindow = window.open(externalProviderUrl, "Authenticate Account", "location=0,status=0,width=600,height=750");
};
$scope.authCompletedCB = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authService.logOut();
authService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authService.obtainAccessToken(externalData).then(function (response) {
$location.path('/orders');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
}]);
authComplete.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="scripts/authComplete.js"></script>
</body>
</html>
authComplete.js
window.common = (function () {
var common = {};
common.getFragment = function getFragment() {
if (window.location.hash.indexOf("#") === 0) {
return parseQueryString(window.location.hash.substr(1));
} else {
return {};
}
};
function parseQueryString(queryString) {
var data = {},
pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
data[key] = value;
}
return data;
}
return common;
})();
var fragment = common.getFragment();
window.location.hash = fragment.state || '';
window.opener.$windowScope.authCompletedCB(fragment);
window.close();
The issue I am having is that when I run the application on a mobile device (Safari, Chrome for Mobile), the social login window opens in a new tab and the JS function which was intended to pass back the fragment to the main application window does not execute nad the new tab does not close.
You can actually try this behavior on both a desktop and mobile browser through the application:
http://ngauthenticationapi.azurewebsites.net/
What I have tried so far in this context is in the login controller, I modified the function so that the external login url opens in the same window:
$scope.authExternalProvider = function (provider) {
var redirectUri = location.protocol + '//' + location.host + '/authcomplete.html';
var externalProviderUrl = ngAuthSettings.apiServiceBaseUri + "api/Account/ExternalLogin?provider=" + provider
+ "&response_type=token&client_id=" + ngAuthSettings.clientId
+ "&redirect_uri=" + redirectUri;
window.location = externalProviderUrl;
};
And modified the authComplete.js common.getFragment function to return to the login page, by appending the access token provided by the social login as query string:
common.getFragment = function getFragment() {
if (window.location.hash.indexOf("#") === 0) {
var hash = window.location.hash.substr(1);
var redirectUrl = location.protocol + '//' + location.host + '/#/login?ext=' + hash;
window.location = redirectUrl;
} else {
return {};
}
};
And in the login controller, I added a function to parse the querystring and try to call the $scope.authCompletedCB(fragment) function like:
var vm = this;
var fragment = null;
vm.testFn = function (fragment) {
$scope.$apply(function () {
if (fragment.haslocalaccount == 'False') {
authenticationService.logOut();
authenticationService.externalAuthData = {
provider: fragment.provider,
userName: fragment.external_user_name,
externalAccessToken: fragment.external_access_token
};
$location.path('/associate');
}
else {
//Obtain access token and redirect to orders
var externalData = { provider: fragment.provider, externalAccessToken: fragment.external_access_token };
authenticationService.obtainAccessToken(externalData).then(function (response) {
$location.path('/home');
},
function (err) {
$scope.message = err.error_description;
});
}
});
}
init();
function parseQueryString(queryString) {
var data = {},
pairs, pair, separatorIndex, escapedKey, escapedValue, key, value;
if (queryString === null) {
return data;
}
pairs = queryString.split("&");
for (var i = 0; i < pairs.length; i++) {
pair = pairs[i];
separatorIndex = pair.indexOf("=");
if (separatorIndex === -1) {
escapedKey = pair;
escapedValue = null;
} else {
escapedKey = pair.substr(0, separatorIndex);
escapedValue = pair.substr(separatorIndex + 1);
}
key = decodeURIComponent(escapedKey);
value = decodeURIComponent(escapedValue);
data[key] = value;
}
return data;
}
function init() {
var idx = window.location.hash.indexOf("ext=");
if (window.location.hash.indexOf("#") === 0) {
fragment = parseQueryString(window.location.hash.substr(idx));
vm.testFn(fragment);
}
}
But obviously this is giving me an error related to angular (which I have no clue at the moment):
https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest
So, pretty much it is a dead end for me at this stage.
Any ideas or input would be highly appreciated.
Gracias!
Update: I managed to resolve the Angular error about the rootscope being thrown, but sadly, resolving that does not fix the main issue. If I tried to open the social login on the same browser tab where my application is, Google can login and return to the application and pass the tokens required. It is a different story for Facebook, where in the Developer's tools console, there is a warning that seems to stop Facebook from displaying the login page.
Pretty much, the original method with which a new window (or tab) is opened is the way forward but fixing the same for mobile browser seems to be getting more challenging.
On desktop, when the auth window pops up (not tab) it has the opener property set to the window which opened this pop up window, on mobile, as you said, its not a pop up window but a new tab. when a new tab is opened in the browser, the opener property is null so actually you have an exception here:
window.opener.$windowScope.authCompletedCB
because you can't refer the $windowScope property of the null value (window.opener) so every line of code after this one wont be executed - thats why the window isn't closed on mobile.
A Solution
In your authComplete.js file, instead of trying to call
window.opener.$windowScope.authCompletedCB and pass the fragment of the user, save the fragment in the localStorage or in a cookie (after all the page at authComplete.html is in the same origin as your application) using JSON.stringify() and just close the window using window.close().
In the loginController.js, make an $interval for something like 100ms to check for a value in the localStorage or in a cookie (don't forget to clear the interval when the $scope is $destroy), if afragment exist you can parse its value using JSON.parse from the storage, remove it from the storage and call $scope.authCompletedCB with the parsed value.
UPDATE - Added code samples
authComplete.js
...
var fragment = common.getFragment();
// window.location.hash = fragment.state || '';
// window.opener.$windowScope.authCompletedCB(fragment);
localStorage.setItem("auth_fragment", JSON.stringify(fragment))
window.close();
loginController.js
app.controller('loginController', ['$scope', '$interval', '$location', 'authService', 'ngAuthSettings',
function ($scope, $interval, $location, authService, ngAuthSettings) {
...
// check for fragment every 100ms
var _interval = $interval(_checkForFragment, 100);
function _checkForFragment() {
var fragment = localStorage.getItem("auth_fragment");
if(fragment && (fragment = JSON.parse(fragment))) {
// clear the fragment from the storage
localStorage.removeItem("auth_fragment");
// continue as usual
$scope.authCompletedCB(fragment);
// stop looking for fragmet
_clearInterval();
}
}
function _clearInterval() {
$interval.cancel(_interval);
}
$scope.$on("$destroy", function() {
// clear the interval when $scope is destroyed
_clearInterval();
});
}]);

Not able to append data to Div and redirect page

I have a default page with list of items. When I click on those Items I need to dynamically append data to div in Page B and redirect the app to Page B.
I added this div in PageB
''
On Click event I am doing following action in .js file:
'$(document).on('click', '#selectConcept', function (node) {
var ncid = this.textContent.slice(6,25);
$.ajax({
dataType: "json",
url: "http://txv-trmindexer01:8080/CommonTerminologyLeopardSearch/rest/getConceptByNcid/" + ncid,
error: function () {
alert("ERROR");
},
success: function (data) {
window.location.href = 'getfacets.html';
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
} });
});'
I am able to redirect page, but nothing is appended to Div.
Can anyone help me out with this..
I'm not really sure, but I guess the code runs before the new page is loaded. So you could try to wrap the code in a function run at onload event time
window.location.href = 'getfacets.html';
window.onload = function() {
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
}
The problem:
As soon as you set "window.location.href" property the page navigates to your page B and you loose your fetched data.
You have two solutions to the problem:
Use Single Page Application (SPA) application approach wherein you could create a new global scope for your fetched data, which can now be used by page B
Send the ncID as a querystring parameter to page B and and implement the service call and data appending logic on page B

Categories

Resources