Ways to display specific HTML content using ng-show according to the current route?

I have a single page using Angular and the layout is as follows:

https://i.sstatic.net/XvPQO.png

When I click on a tab, for example "Services", the services content is displayed below the tabs.

Below is the relevant code snippet:

<a href ng-click="tab.setTab(4)">Services</a>

....

<perfil-content ng-show="tab.isSet(2)"></perfil-content>

  <brand-content ng-show="tab.isSet(3)"></brand-content>

  <service-content ng-show="tab.isSet(4)"></service-content>

All of this is within a single route, for example: http://localhost:9000/#/

Now, what I want is that when http://localhost:9000/#/services is accessed, the services content should be displayed just like when it is clicked.

I tried the following code:

<service-content ng-show="location.hash == '#/services'">

but it does not work properly.

Any help on this would be greatly appreciated. Thank you!

Answer №1

To effectively tackle this issue, the recommended approach is to utilize ui.router. Establish a state for each tab and then employ it accordingly. For more detailed information on the application of ui-router, refer to this link.

Configuration

app.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
  .state("shell", {
   url: "",
   templateUrl: "/shell.html"
  })
 .state("shell.services", {
   url: "/services",
   controller: "servicerCtrl",
   templateUrl: "/services.html"
 })
.state("shell.profiles", {
   url: "/profiles",
   controller: "servicerCtrl",
   templateUrl: "/services.html"
});
});

Shell.html

<ul>
  <li href="/services">Services</li>
  <li href="/services">Profiles</li>
</ul>
<ui-view></ui-view>

Alternatively, if you opt not to use ui-router, you can inject $route, $routeParams into your controller to extract the route from there. Subsequently, based on that route, set the necessary conditions in your HTML structure. Nonetheless, it is strongly recommended to leverage ui-router as the preferred solution.

Answer №2

My perspective aligns with the consensus in previous responses, utilizing ui-router would prove to be much more efficient in this scenario. This framework also offers a helpful filter known as isState, which can be implemented as shown below:

<perfil-content ng-show="{{'perfil' | isState}}"></perfil-content>

<brand-content ng-show="{{'brand' | isState}}"></brand-content>

<service-content ng-show="{{'service' | isState}}"></service-content>

By following this approach, it automatically showcases the appropriate component based on the current state. It is important to ensure that your states are correctly named as perfil, brand, and service.

Answer №3

Implementing parent and child states with ui.router is a more elegant solution. I decided to experiment with it using $location

Check out this code snippet below. Feel free to test it out on plnkr.

http://plnkr.co/edit/ABC123XYZ

// Your code can go here

var app = angular.module('myApp', []);

app.controller('MyCtrl', function($location) {
  this.checkTab = function(tabName) {
    return $location.path() === '/' + tabName;
  };
});
<!DOCTYPE html>
<html ng-app='myApp'>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
  <link href="style.css" rel="stylesheet" />
  <script src="script.js"></script>
</head>

<body ng-controller='MyCtrl as ctrl'>
  <h1>Welcome to Plunker!</h1>
  <a href="#/tab1">Tab 1</a>
  <a href="#/tab2">Tab 2</a>
  <a href="#/tab3">Tab 3</a>
  <a href="#/tab4">Tab 4</a>

  <div ng-show='ctrl.checkTab("tab1")'>
    <p>Content for tab 1</p>
  </div>
  <div ng-show='ctrl.checkTab("tab2")'>
    <p>Content for tab 2</p>
  </div>
  <div ng-show='ctrl.checkTab("tab3")'>
    <p>Content for tab 3</p>
  </div>
  <div ng-show='ctrl.checkTab("tab4")'>
    <p>Content for tab 4</p>
  </div>
</body>

</html>

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

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

Opt for specific data by default when working with multi data series on c3 charts

Looking at this complex multi-data chart depicted in the image here: https://i.sstatic.net/Gpz52.png The C3 chart displayed all data series by default and visualized them together on the chart. Is there a method available to pre-select one or two data se ...

How can you elevate an HTML element to the front using the "z-index" property or the "append" method?

When working with HTML documents, we often come across various HTML elements like div, p, img, and more. Many of these elements are dynamically created, especially if helpful CSS such as "position: absolute;" is used. After every onClick event, it is nec ...

Tips for identifying the extreme points (minimum and maximum) within a fluctuating interval

With an array of length 200, a new number is added to position [0] every second, pushing the other values up one position in the array. I am looking for a way to determine the maximum and minimum values of the entire array each time a new number is added. ...

JavaScript - Populate canvas with selected image from gallery upon clicking an image

A photo gallery on my website is filled with images fetched from a local directory using PHP. I would like users to be able to select an image by clicking on it and then have the option to draw on that image within a canvas element. The gallery has been c ...

Stream video files using NodeJS and seamlessly switch between audio tracks

I am looking to stream a video on my PC through a browser using nodejs. I found a helpful guide on how to achieve this using express, which can be found at this link: https://medium.com/better-programming/video-stream-with-node-js-and-html5-320b3191a6b6 (P ...

Is there a way to use JQuery to make one button trigger distinct actions in two different divs?

For instance: Press a button - one div flies off the screen while another div flies in. Press the button again - Same div flies out, other div returns. I'm completely new to Javascript/JQuery so any assistance would be highly appreciated! Thank you ...

Passing User Authentication State from Express/Passport to a React Client: A Step-by-Step Guide

I want to pass a basic boolean value const isLoggedIn = true; (provided by Passport) from my Express backend to my React frontend. I'm looking for an alternative to embedding it in the HTML through a templating engine. This seems like a common req ...

Unresponsive jQuery dialog during Ajax request

Currently, I have the setup so that a dialog box pops up when an AJAX post is successful. The AJAX post itself is successful as the alert shows, but for some reason, the dialog box doesn't appear. I'm struggling to understand why this is happenin ...

Choosing a specific option from a list of multiple choices with javascript

I have a selection with multiple options. Currently, the selected values are '2,4,5'. <select id="testID" multiple="multiple"> <option value="1">test Value1</option> <option value="2">test Value2</option> ...

Is there a way to identify extensive usage of JavaScript on a webpage using Python, Scrapy, and Selenium?

After creating a Scrapy spider to handle Javascript content on webpages using Selenium, I noticed that it was much slower compared to a traditional Scrapy Crawler. To speed up the process, I am considering combining two spiders: utilizing the common CrawlS ...

Utilizing AngularJS for a Simple AJAX GET Request

I'm currently developing a Chrome extension with Angular JS. My goal is to retrieve and parse an HTML page from a third-party website. When using Angular JS $resource to achieve this (is there a more effective method?), I encountered an unusual objec ...

Determine the exact width of text without rounding in Javascript

I'm facing an issue with a div element that I'm manipulating using Javascript to change its position. The problem is that it's rounding off incorrectly. #hi{ background-color: blue; width: 2px; height: 10px; position: absolu ...

Ways to trigger various functions upon alteration of minimum and maximum values in a range slider bar

I am currently working on an app that features a range seek bar. My objective is to invoke a method passing the minimum value of the bar if it has been changed, and likewise to trigger another method passing the maximum value if it has been changed. Below ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Looking for search suggestion functionalities in an HTML input field

I am currently working on a website project and have a database filled with recipes to support it. The issue I am facing is related to the search feature on my webpage. At the top of the page, there is a textarea where users can input their search queries ...

Achieving left alignment for Material-UI Radio buttons: Float them left

Click here to view the demo https://i.stack.imgur.com/Yt4ya.png Check out the demo above to see the code in action. I'm currently struggling to align the radio buttons horizontally, wondering if there's an easier way to achieve this using Mater ...

A guide on accessing information from a post form using an express.js server

Issue: Whenever the client submits a form using a post request to the server, the express server receives an empty body (req.body = {}). Objective: My goal is to retrieve req.body.username and req.body.password on a post request from the client (using the ...

React App PWA ERROR: Service worker not registered to control the page and start_url

I am encountering an issue while building a progressive web app using Create React App. Lighthouse benchmarking results in an error, indicating that my PWA is not installable. Surprisingly, I face the same problem even when utilizing the official PWA templ ...

The combination of Ajax, JavaScript, PHP/HTML, and dynamic variables

Hey there, I'm currently working on a game development project and have encountered what seems to be a scope issue. The issue arises in my js file when a player clicks on the card they want to play: It starts in my js file:</p> <pre>&l ...