Selecting tabs in Angular with a controller function

I'm currently working on implementing AngularJS to show the tab number when a specific tab is selected using the controller method. However, it's not working as expected. Any assistance on this issue would be greatly appreciated.

HTML

<body ng-app="coolApp">
    <section ng-controller="panelSelector as panel">
        <ul class="nav nav-pills">
            <li ng-class="{active:panel.isSet(1)}"><a href ng-click="panel.setTab(1)">Concert Band</a></li>
            <li ng-class="{active:panel.isSet(2)}"><a href ng-click="panel.setTab(2)">Ceremonial Band</a></li>
            <li ng-class="{active:panel.isSet(3)}"><a href ng-click="panel.setTab(3)">191st Jazz Combo</a></li>
            <li ng-class="{active:panel.isSet(4)}"><a href ng-click="panel.setTab(4)">Brass Ensemble</a></li>
            <li ng-class="{active:panel.isSet(5)}"><a href ng-click="panel.setTab(5)">Celtic Fire</a></li>
        </ul>
        <p> The tab number displayed is: {{tab}}</p>
    </section>
</body>

Code

var app = angular.module("coolApp", []);
app.controller("panelSelector", function(){
this.tab = 1; 

this.setTab = function(tabChoice){
    this.tab = tabChoice;
};
this.isSet = function(checkTab){
    return this.tab === checkTab;
};
});

Answer №1

var app = angular.module("coolApp", []);
app.controller("panelSelector", function(){
  var panel = this;
  panel.tab = 1; 

  panel.setTab = function(tabChoice){
      panel.tab = tabChoice;
  };
  panel.isSet = function(checkTab){
      return panel.tab == checkTab;
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<body ng-app="coolApp">
<section ng-controller="panelSelector as panel">
            <ul class = "nav nav-pills">
                <li ng-class="{active:panel.isSet(1)}"><a href ng-click = "panel.setTab(1)">Concert Band</a></li>
                <li ng-class="{active:panel.isSet(2)}"><a href ng-click = "panel.setTab(2)">Ceremonial Band</a></li>
                <li ng-class="{active:panel.isSet(3)}"><a href ng-click = "panel.setTab(3)">191st Jazz Combo</a></li>
                <li ng-class="{active:panel.isSet(4)}"><a href ng-click = "panel.setTab(4)">Brass Ensemble</a></li>
                <li ng-class="{active:panel.isSet(5)}"><a href ng-click = "panel.setTab(5)">Celtic Fire</a></li>
            </ul>
            <p> the tab number is: {{panel.tab}}</p>
</section>
</body>

  • Your use of panel with this was incorrect,
  • You were displaying {{tab}} instead of {{panel.tab}} to show the selected tab,

  • And your return statement should have been return panel.tab == checkTab;.

Hope that fixes the problem!

Answer №2

The values of this inside the setTab and isSet functions are not the same. It is recommended to declare a variable and assign this before using it.

Controller

var app = angular.module("coolApp", []);
app.controller("panelSelector", function(){
  var panel = this;
  panel.tab = 1; 

  panel.setTab = function(tabChoice){
      panel.tab = tabChoice;
  };
  panel.isSet = function(checkTab){
      return panel.tab == checkTab;
  };
});

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

Removing data using axios in a React project

I'm currently working on a small app using the Json server package to help me keep track of movies I want to watch in my free time. I am looking to learn React and Axios, so I decided to build this app with these technologies. The concept is simple - ...

What is the best way to prevent a folder from being included in the next js build process while still allowing

I am faced with a challenge involving a collection of JSON files in a folder. I need to prevent this folder from being included in the build process as it would inflate the size of the build. However, I still require access to the data stored in these file ...

Tips for transferring values between functions within the same scope

Currently, I am facing an issue where I have two functions within the same controller and I am attempting to pass a value from one function to another. Unfortunately, I keep receiving an error that says TypeError: Cannot read property 'activeDataset&a ...

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

Struggling to properly bind data to this variable in AngularJs

Two Key Points to Note: 1. I am aiming to steer clear of using $scope as it may hinder the new "controller as" syntax. 2. It appears that my issue could be related to variable scope, so clarifying the correct JS approach might resolve the problem. Disrega ...

What is the reason for including parentheses when evaluating JSON data?

What is the purpose of adding ( and ) around the code when using eval? var strJson = eval("(" + $("#status").val().replace(";","") + ")"); Note: The result of $("#status").val() is similar to {"10000048":"1","25000175":"2","25000268":"3"}; ...

Tips on setting up a dropzone upload feature with a click-trigger option

Is there a way to configure dropzone.js so that the file is uploaded only when a submit button is clicked, rather than automatically? Here's the code snippet I am currently using: $('#myDropzone').dropzone({ url: SITE_URL + 'self_r ...

Is there a way in AngularJS to refresh a route and re-execute the $routeProvider resolve function?

Allow the user to choose an option that influences the controller's dependencies. When the user changes this option, I would like to refresh the route while still executing the resolve section of $routeProvider. Using $route.reload() only refreshes t ...

The issue of a parent list item onclick function overpowering the onclick function of a sub list item within AngularJS

Here is an excerpt from the template I am working on: <ul> <li ng-repeat="a in alist" ng-click="toggleShowItems(a)"> {{a.name}} <ul ng-if="a.showItems" > <li ng-repeat="item in a.items" ng-click="show ...

Utilizing AJAX to dynamically update a div on a separate webpage

In my application, I have a page called news.jsp that displays a list of news titles. Users can click on a title to read the full body of the news, which is loaded using AJAX within a span tag on the same page. Additionally, I display the top 5 news storie ...

The tablet is having trouble playing the mp3 audio file

When clicking on an mp3 audio file, I want the previous file to continue playing along with the new one. While this works perfectly on browsers with Windows machines, there seems to be an issue when using a tablet. The second mp3 stops playing when I clic ...

Is the text in bold format or not detectable in contenteditable mode?

I am currently working on developing a custom text editor using the built-in contenteditable feature in HTML. I am trying to figure out how to determine whether the selected text is bold or not within the editor. This is what my current setup looks like: ...

Modify data source with AngularJS when clicking a button

I have a webpage with a controller called 'listCtrl' that fetches data from "http://data.com/?region=north". app.controller('listCtrl', function ($scope, $http) { $http.get("http://data.com/?region=north").success(function (data) { ...

The console is throwing an error: ReferenceError: The variable $ has not been defined

I am having issues when trying to dynamically add a div upon selecting a checkbox in a Django template. The error message Uncaught ReferenceError: $ is not defined keeps appearing in the console. Here is the template code: {% extends 'base_layout.htm ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

How to select the first column in a jQuery Datatable and turn it into checkboxes

I'm faced with a situation where I need to incorporate a checkbox column in a table, with the checkboxes appearing as Checked or Unchecked based on the values in the first column and its subsequent rows. The challenge lies in dealing with dynamic data ...

Tips on how to dynamically update information with Angular

Looking to dynamically update data when a user selects an option from a dropdown menu using the Angular framework This is what I currently have: <div> <button type="button"> {{tests[0].test}} </button> <ul c ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

I have a website hosted on Heroku and I am looking to add a blog feature to it. I initially experimented with Butter CMS, but I found it to be too pricey for my budget. Any suggestions on

I currently have a website running on Heroku with React on the front end and Node.Js on the back end. I want to incorporate a blog into the site, but after exploring ButterCMS, I found the pricing starting at $49 to be too steep for my budget. My goal is ...

How can we effectively share code between server-side and client-side in Isomorphic ReactJS applications?

For a small test, I am using express.js and react.js. Below you can find my react code: views/Todo.jsx, var React = require('react'); var TodoApp = React.createClass({ getInitialState: function() { return { counter: 0 ...