The ng-click function within the template functions correctly initially, but ceases to work upon returning to the page

I am working on a Single page app website and I need the menu tab to change its class to active when a specific page is selected. The issue arises in my home.html template where I have an <a> tag linking to the history page. The goal is for the history menu item to have an active class when this link is clicked. Initially, it works fine when the site is first loaded, but subsequent attempts do not result in the expected behavior if the user navigates back and forth between the history page and the home page. Any suggestions?
Please note that both the menu and the home content are templates that have been included using ng-include and ui-view (via ui-router).

<body onresize="setWidth()" ng-app="app" ng-controller="changeTab">

<div data-role="page" >

 <!--include the menuTemplate set the current index to appropriate value-->
 <div ng-include="'templates/menuTemplate.html'"></div>

</div>
 <div data-role="main" class="ui-content">
  <div ui-view></div>
 </div>
</body>

menuTemplate.html:

<nav class="navbar navbar-default" id="desktopNav">
  <div class="container-fluid">
    <div class="topNav">
      <ul class="nav navbar-nav">
       <li ng-click="setIndex(0)" ng-class="(index==0)? 'active':''"><a id="homeButton" ui-sref="home">Home</a></li>
       <li ng-click="setIndex(1)" ng-class="(index==1)? 'active':''"><a ui-sref="history">History</a></li>
       <li ng-click="setIndex(2)" ng-class="(index==2)? 'active':''"><a ui-sref="ensembles">Ensembles</a></li>
       <li ng-click="setIndex(3)" ng-class="(index==3)? 'active':''"><a ui-sref="staffs">Staffs</a></li>
       <li ng-click="setIndex(4)" ng-class="(index==4)? 'active':''"><a ui-sref="career">Career</a></li>
       <li ng-click="setIndex(5)" ng-class="(index==5)? 'active':''"><a ui-sref="contact">Contact</a></li>
     </ul>
   </div>
 </div>
</nav>

home.html (VIEW) template:

<p><a href="history" ng-click="setIndex(1)">Learn more...</a></p>

Angular JS:

angular.module('app').controller('changeTab',['$scope', function($scope){
  $scope.index;

  $scope.setIndex = function(val){
    $scope.index=val;
  }

  $scope.getIndex = function(val){
    return $scope.index;
  }
}]);

Answer №1

Using ui-sref-active attribute eliminates the need for ng-click and ng-class:

<nav class="navbar navbar-default" id="desktopNav">
  <div class="container-fluid">
    <div class="topNav">
      <ul class="nav navbar-nav">
       <li ui-sref-active="active"><a id="homeButton" ui-sref="home">Home</a></li>
       <li ui-sref-active="active"><a ui-sref="history">History</a></li>
       <li ui-sref-active="active"><a ui-sref="ensembles">Ensembles</a></li>
       <li ui-sref-active="active"><a ui-sref="staffs">Staffs</a></li>
       <li ui-sref-active="active"><a ui-sref="career">Career</a></li>
       <li ui-sref-active="active"><a ui-sref="contact">Contact</a></li>
     </ul>
   </div>
 </div>
</nav>

Answer №2

In order to prevent the main controller from constantly resetting the $scope.index value, it is important to develop distinct controllers for both navigation templates and page templates.

Answer №3

Just gave ui-sref-active a shot based on @Danial's suggestion, and it worked perfectly :)

angular.module('demo', ['ui.router']);
angular.module('demo')
  .config(function($stateProvider, $urlRouterProvider) {
    // default state
    $urlRouterProvider.otherwise("/home");
    $stateProvider
      .state('home', {
        url: "/home",
        template: "<h3>This is home.</h3>"
      })
      .state('career', {
        url: "/career",
        template: "<h3>Career.</h3>"
      })
      .state('contact', {
        url: "/contact",
        template: "<h3>Contact.</h3>"
      });
  })
  .controller('MenuCtrl', ['$log',
    function($log) {

      $log.debug('MenuCtrl activated');
    }
  ]);
.nav {
  margin: 0;
  padding: 0;
}
.nav li {
  display: inline-block;
  padding: 5px
}
.active {
  background-color: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.min.js"></script>
<div ng-app="demo" ng-controller="MenuCtrl as menu">
  <nav class="navbar navbar-default" id="desktopNav">
    <div class="container-fluid">
      <div class="topNav">
        <ul class="nav navbar-nav">
          <li ui-sref-active="active"><a ui-sref="home">Home</a>
          </li>
          <li ui-sref-active="active"><a ui-sref="career">Career</a>
          </li>
          <li ui-sref-active="active"><a ui-sref="contact">Contact</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>
  <div ui-view></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular: Executing a function within the controller's scope and subsequently transferring it to a directive

I am currently working on evaluating a function in the parent controller and passing it into a directive. It is important that these values are watched by the digest loop and updated whenever a user makes changes. While I have resolved some initial issues ...

Bring div button on top of the contenteditable field

I am working on an Angular app for a client and need to implement a clickable button at the bottom right of a contenteditable element, similar to the image shown below : https://i.sstatic.net/J6XdW.png The challenge is that the content needs to be scroll ...

Redirect based on the geographical location of IP addresses (Geo-IP)

This code displays the page during execution and then initiates a redirect. Unfortunately, the redirection process is not as fast as desired. This application was created on blogspot.com <script> fetch('https://freegeoip.app/ ...

unable to attach picture to the img element

Currently, I am honing my skills in Windows Phone development through WinJS. In my latest project, I have crafted a code snippet that parses JSON data fetched from a specific URL. The objective is to bind the images retrieved to a list view on an HTML page ...

Wait for the completion of a Promise inside a for-loop in Javascript before returning the response

After completing a Promise within a for-loop, I am attempting to formulate a response. Although I have reviewed these questions, my scenario remains unaddressed. The methodGetOrders and methodGetLines are components of an external library that must be ut ...

Is there a universal method to disregard opacity when utilizing jQuery's clone() function across different web browsers?

I've encountered a situation where I need to allow users to submit a new item to a list within a table, and have it smoothly appear at the top of the list. While using DIVs would make this task easier, I am working with tables for now. To achieve thi ...

Encountering a TypeError when implementing $cookies in a controller: undefined function error occurs

UPDATE: RESOLVED ISSUE It turns out that I mistakenly thought ngCookies was a built-in part of angular.js, but in reality it is a separate service. The problem was with my bower.json file which referenced angular 1.4beta while loading angular-cookies for ...

Seeking assistance in structuring the logic for an AngularJS app

As a beginner with Angular, I am seeking guidance on the best practices for structuring my code in the angular way. This question is more about the overall structure rather than specific technical details. In my application, data needs to be fetched from ...

Use JavaScript and PHP to retrieve a value from an array and dynamically populate select options based on that value

In my PHP code, I have two arrays structured like this: Array ( [0] => 11 [1] => 11 [2] => 11 [3] => 11 [4] => 11 [5] => 187 ) Array ( [0] => 118 [1] => 112 [2] => 85 [3] => 81 [4] ...

Pinia throws a useStore is not callable error

I have been trying to resolve the issue with (0 , pinia__WEBPACK_IMPORTED_MODULE_1__.useStore) is not a function but unfortunately, I haven't been able to find a solution. Can anyone point out what mistake I am making? Here is my store.js code: im ...

Submit the form with an input value that is located outside of the form

I am facing an issue with a dropdown menu that displays a list of users. When I select a user from the list, a radio button appears with options to Modify user details, Change user Permissions, or Warn User. After choosing an option from the radio buttons ...

The first ajax request went off without a hitch, but the second one hit a snag and displayed a parse error

I am facing an issue with two Ajax calls that have similar lines but only one of them seems to be working correctly. First Ajax post : $("#languageswitcher").change(function(){ var locale=$(this).val(); //alert(111); //console.log(111) ...

Struggling to Make This PHP Ajax Autocomplete Example Work

I watched a tutorial on YouTube that demonstrated exactly what I am attempting here. However, I am having trouble getting it to function properly. I am using the following resources: I have placed all the necessary files directly under the project folders ...

Angular integrated with DOJO application

I'm currently working on incorporating Angular into an existing DOJO application. I've set up a plunkr http://plnkr.co/edit/8pgdNwxFoxrDAQaQ4qfm?p=preview, but unfortunately, the angular module is not loading. Can anyone provide guidance on what ...

What is the best way to access the methods in the "parent" class?

I am facing a situation where I have an object with fieldsCreators that hold creator methods for each field. The dilemma is how to call the creator method inside fieldsCreators as shown below: var obj={ creator:function(ch) { .... .. ...

What is the reason that the reduce function is only effective when the final argument is explicitly stated?

I'm having trouble understanding the reduce method. What is the reason why const sumOfCubes = nums => nums.reduce((a,b) => a + Math.pow(b, 3)) does not function properly, while const sumOfCubes = nums => nums.reduce((a,b) => a + Math.po ...

Angular.js can efficiently handle waiting for multiple resource calls and AJAX requests

I'm facing a challenge in my Angular.js application where I need to make three separate resource calls and then use the data together once all the requests are complete. Here are the three calls I need to make: # Retrieve the curriculum $scope.curric ...

Error message: "Uncaught ReferenceError: $ is not defined in BackboneJS and RequireJS"

In my Backbone application, I am using RequireJS. However, I keep encountering the error message Uncaught ReferenceError: $ is not defined, indicating that my libraries may not be loading properly. This is what my RequireJS config looks like: require.con ...

I'm having trouble getting EJS files to run JavaScript module scripts

I am facing an issue with my ejs file running on localhost. I am trying to execute functions from other files that are imported with js. In the ejs file, there is a module script tag which successfully executes the code of the file specified in the src att ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...