jQuery doesn't run on first page load, but it's fine on refresh?

Viewed 9

I have an issue within AngularJS/ServiceNow's Service Portal where I have this 'Tabber' widget that hides/shows different containers on the page, but the logic never actually fires the first time I load up a page. Everything works fine after the page loads, and even after I refresh the page, but that first page load never actually hides anything. Here's my code, and before someone mentions it, yes, I know you're not supposed to use jQuery in the Client Controller, but I couldn't get this level of responsiveness/dynamicism in the Link function, so I elected to break the rules.

Client Controller

    api.controller=function($scope, $rootScope) {
  /* widget controller */
  var c = this;
        
    /* Based on the Tab Selected, uses $scope.data.tabs to show or hide specified containers.*/
    $scope.openTab = function(tabName) { // Nothing in here works on first page load. No logs, nothing.
        $scope.data.selectedTab = tabName;
        
        var i = 1; // 'i' starts at 1 to mirror the 'order' field of containers displayed in Page Designer.
        // Show/hide individual containers based on whether or not they're referenced in the tabs object.
        jQuery(".container").each(function() {
            var showTab = false;
            var tabsContainsIndex = false;
            for (var j = 0; j < $scope.data.tabs.length; j++) {
                var tab = $scope.data.tabs[j];
                if (!tab.hasOwnProperty("containers")) continue;
                if (tab.containers.includes(i)) {
                    tabsContainsIndex = true;
                    if (tab.label != tabName) continue;
                    showTab = true;
                    //console.log("For Container " + i + ", found Tab " + tab.label + ", matching tabName " + tabName + "; Containers: " + tab.containers.toString());
                    break;
                }
            }
            //console.log("For Container " + i + " and Tab: " + tab.label + ", TabFound = " + tabsContainsIndex + "; showTab = " + showTab);
            if (tabsContainsIndex && showTab) {
                //console.log("TabFound = True, ShowTab = True. Showing Container " + i);
                jQuery(this).show();
            }
            if (tabsContainsIndex && !showTab) {
                //console.log("TabFound = True, ShowTab = False. Hiding Container " + i);
                jQuery(this).hide();
            }
            i++;
        });
    };
    
    /* Default the selected Tab on Load. */
    if ($scope.data.selectedTab) $scope.openTab($scope.data.selectedTab); // This doesn't run on the first page load, with or without logs. 
};

For additional context, I've also tried a variation on this same code within the Link function, but it hasn't fixed anything. Any help would be greatly appreciated.

0 Answers
Related