Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Service Portal, $location. Works on page reload only. Not when URL chanes

amwebaz
Kilo Expert
I am working in the Service Portal. The script below works on page reload or refresh. 
However with I click a link on the page that changes the url, for instance like on a
single page application. The script does not fire. Can this be done in AngularJS?
If so how can that be done? Or should this JavaScript be done differently?
Thanks in advance for you wisdom and help.

<script
type="text/javascript"> $(document).ready(function () { if(window.location.href.indexOf("table=sc_cat_item") > -1) { alert("your url contains the name table=sc_cat_item"); } }); </script>
1 ACCEPTED SOLUTION

I had mentioned this in the other post as well, but you don't need the ( at the beginning of the client controller or the )(); at the end of it. those are probably causing your issues.

View solution in original post

13 REPLIES 13

Jon Barnes
Kilo Sage

Yes, I have done this before. you can put the below snippet into your header or footer client controller. it needs to be in the header or footer because those widgets only load the first time the page is refreshed and don't reload after that. make sure you add $location to your function parameters of your client controller:

function checkLocation() {
  var loc = $location.search();
  if (loc.table == 'sc_cat_item') {
     // add whatever logic you need here.
  }
}

$scope.$on('$locationChangeSuccess',function() {
  checkLocation();
});

// that trigger above won't run the first time the page is loaded, so call it in the widget on load as well:
checkLocation();

Thank you for the response. But the code is not being recognized. 

Below is my client script:

(function() {
/* widget controller */
var c = this;

function checkLocation() {
var loc = $location.search();
if (loc.table == 'sc_cat_item') {
alert("works");
}
}

$scope.$on('$locationChangeSuccess',function() {
checkLocation();
});

})();

 

 

in my HTML I have included 

onload="checkLocation()

 

Don’t put onload=checkLocation(); because that will cause an error. Do it like this as I put in my initial response (function($location) { /* widget controller */ var c = this; function checkLocation() { var loc = $location.search(); if (loc.table == 'sc_cat_item') { alert("works"); } } $scope.$on('$locationChangeSuccess',function() { checkLocation(); }); checkLocation(); })();

Yes, I have the code here exactly this way in the "Widget Client Script"

The alert does not show.

 

(function($location) {
/* widget controller */
var c = this;

function checkLocation() {
var loc = $location.search();
if (loc.table == 'sc_cat_item') {
alert("works");
}
}


$scope.$on('$locationChangeSuccess',function() {
checkLocation();
});

checkLocation();
})();