What is the most effective method for structuring code to display or conceal HTML based on the root in AngularJS?

Currently, I am utilizing Angular to create a quiz. The root for Questions is /#/questions/1.

With a total of 6 questions, I am displaying and hiding HTML for each question based on the root. Here is how my code appears:

Template

<section ng-class="{active:isActive(1)}">
    Question 1
</section>
<section ng-class="{active:isActive(2)}">
    Question 2
</section>
<section ng-class="{active:isActive(3)}">
    Question 3
</section>
<section ng-class="{active:isActive(4)}">
    Question 4
</section>
<section ng-class="{active:isActive(5)}">
    Question 5
</section>
<section ng-class="{active:isActive(6)}">
    Question 6
</section>

Question controller

$scope.isActive = function(question) {
    return question === Number($routeParams.id);
}

Is there a more dynamic way of avoiding the use of hard-coded section indexes? Perhaps something along the lines of the jQuery index functionality?

Answer №1

Have you considered utilizing ng-repeat with $index to establish this?

Include something like this in the controller:

$scope.questionsNumber = new Array(6)

Then, in the template, make the following changes (Note: this is pseudo code, not tested, refer to ng-repeat documentation for specifics):

   <section ng-repeat="i in questionsNumber track by $index" ng-class="{active:isActive($index)}">
       Question {{$index}}
   </section>

You may need to utilize a function instead of questionsNumber as discussed in this question

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

Resize a group of images to match the parent's width and height dimensions

I am working with a div that contains variously-sized images and is nested inside a parent container. <div id="parentContainer"> <div id="boxToScale"> <img src="http://placehold.it/350x150" /> <img src="http://placehold.it/150 ...

Shader material for border and overlay effects in THREE.js

Can a sphere in THREE.js be given a material shader to achieve a unique visual effect like the one shown here? (I'm specifically interested in replicating the border, glow, and streak on the red sphere.) https://i.sstatic.net/rjfkm.png If this is po ...

Using React to simulate API calls outside of testing environments

For instance, I encounter issues when certain endpoints are inaccessible or causing errors, but I still need to continue developing. An example scenario is with a function like UserService.getUsers where I want to use fake data that I can define myself. I ...

A more efficient method for refreshing Discord Message Embeds using a MessageComponentInteraction collector to streamline updates

Currently, I am working on developing a horse race command for my discord bot using TypeScript. The code is functioning properly; however, there is an issue with updating an embed that displays the race and the participants. To ensure the update works co ...

Tips for customizing ngTable with expandable detail panels

I am currently working on styling a layout using ng-table, which includes a table within each row. The expanding functionality in Angular is implemented as follows: <tr ng-if="org.expanded" ng-repeat-end> <td></td> <td></td& ...

Information submitted through an ajax request does not get saved in the $_POST array

After successfully executing an AJAX request using GET, I decided to try POST this time. However, when attempting to send data, a baffling error message appeared in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does ...

Loading values from an API in an AngularJS module configuration block

I'm working on an app that includes a Facebook login button using the 'angular-facebook' module. In my .config block, I have this code: FacebookProvider.init('myAppId'); However, I need to load the myAppId from a database using a ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Show only upon initial entry: > if( ! localStorage.getItem( "runOnce" ) ) { activate anchor link

My JavaScript form performs calculations, but I only want it to display the first time a visitor enters the site. I attempted to add the following code before my script: jQuery(document).ready(function($) { if( ! localStorage.getItem( "runOnce" ) ) { ...

The hyperlink to a different webpage does not trigger any JavaScript functionalities or render any CSS styles

I am facing an issue with linking HTML pages that run Javascript and JQuery Mobile from another HTML page. My link setup is as follows: <a href="hours.html">Hours</a> The linking page and the linked pages are in the same directory. However, ...

Using data-attribute, JavaScript and jQuery can be used to compare two lists that are ordered

I am looking to implement a feature that allows me to compare two lists using data attributes in either JavaScript or jQuery. Unfortunately, I haven't been able to find any examples of this online and I'm not sure how to approach it. The first l ...

What is the best way to test a try/catch block within a useEffect hook?

Hey, I'm currently dealing with the following code snippet: useEffect(() => { try { if (prop1 && prop2) { callThisFunction() } else { callThatFunction() } ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...

Creating an HTML table on-the-fly leads to the opening of a fresh new webpage

Has anyone encountered this issue before? I have a math table coding function, which runs when a button is clicked. However, when I click the button, the table appears on a new page instead of on the same page. <!doctype html> <html> <h ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

How to transfer input value from textbox to a div using Vue.js

I am attempting to trigger a function when a button is clicked. Furthermore, the value from the text box one should be displayed in a div. Sample code: <input v-model="textdata" type="text" class="w-full rounded"> < ...

Unable to fetch information from the local host using an AJAX request and PHP script

I'm having trouble retrieving the <p> elements echoed in my PHP script. I need a solution that allows me to style these <p> nodes using a JavaScript function without refreshing the page. Can someone help me with this issue? Here is my PHP ...

Textfield removal from the input range is requested

I recently encountered an issue with my input range HTML code. Here is the initial code snippet: <input class="sliderNoTextbox" id="ti_monatlich" type="range" name="ti_monatlich" data-theme="d"> After some adjustments based on this helpful answer, ...

Exploring Vue.JS with Staggered Transitions and Enhancing User Experience with Loading More

The VueJS Guide offers a clever method for using the item's index to create a delayed transition for the items in the data set. You can learn more about it here. While this approach works great when the data set remains static, I'm encountering a ...