Discover the power of Angular JS with the ng-hide and ng-show API!

My webpage has multiple <div> elements, each with a specific user id requirement. For instance, there are div1, div2, div3, and div4 on the page, while I have two users: user1 and user2.

I want to display div1 and div3 when user 1 visits the page, and div2 and div4 for user2 using AngularJS's ng-hide and ng-show directives. What would be the best way to implement this?

Answer №1

To control user access, I recommend setting properties on the $scope within a designated object. These properties can be toggled whenever the user is loaded.

Here's an example implementation assuming the user is loaded when the controller is:

app.controller('SecuredForm', function($scope) {
     // Retrieve user data
     var user = getSomeUser(); 

     // Set user permissions using a hypothetical scenario
     $scope.permissions = {
         showAdmin: user.isRegistered && user.isAdmin,
         showBasic: user.isRegistered,
         showHelp: !user.isBanned
     }
});

In your HTML, you can utilize these scope items to dynamically show or hide specific areas:

<div ng-show="permissions.showAdmin">
  <h3>Admin Area</h3>
  <!-- Admin content here -->
</div>
<div ng-show="permissions.showBasic">
  <h3>Basic Info</h3>
  <!-- Basic content here -->
</div>
<div ng-show="permissions.showHelp">
  <h3>Help</h3>
  <!-- Help content here -->
</div>

Note that ng-show and ng-hide only control the visibility of HTML elements on the client side. It's crucial to validate permissions on the server side when executing actions that require authorization. Displaying elements does not grant users actual permission beyond visual access.

Answer №2

Why don't you try out this jsfiddle? Modify the $scope.userId variable and observe the changes when you click "run" on jsFiddle. Check out the code snippet below:

HTML:

<div ng-app>
    <div ng-controller="DivGroup">
        <div ng-show="getUserId() == 1">Div 1</div>
        <div ng-show="getUserId() == 2">Div 2</div>
        <div ng-show="getUserId() == 1">Div 3</div>
        <div ng-show="getUserId() == 2">Div 4</div>       
    </div>
</div>

JavaScript:

function DivGroup($scope) {

    $scope.userId = 2;

    $scope.getUserId = function() {
        console.log('test');
        return $scope.userId;             
    }
}

When the userId is set to 1, it shows the content of divs one and three. If it's set to 2, it displays the content of divs two and four. ​

Answer №3

The implementation of the true : false, show : hide logic proved to be very effective for me, especially when used as a toggle feature. Check out this link for more information!

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

When using the if-else statement to check the typeof value, it is returning as undefined

update Hello, I conducted a test on your code and found that it breaks for another scenario when the mobileVersion is set as sample.pdf. In this case, I am getting skyCloudmageProfilePic as pdfProfilePic without removing the typeof condition. Here is the ...

Creating a web application that efficiently stores and retrieves user preferences

Currently, I am working on developing a Nodejs/Express web application that is similar to a dashboard or homepage for a web browser. The data displayed on the page is customized based on the user's settings. When a user signs up, I create a json file ...

Sorting through various data inputs in one JSON file

I have a JSON file containing an array of objects: obj= [{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"ten",lanme:"kumar" },{fname:"abhi",age:5,class:"t ...

"Accessing the HTMLDivElement object through document.getElementById will result in [object HTMLDivElement]

When inserting this code snippet into my HTML div: <script> document.getElementById("mArray").appendChild = '<%= mArray %>' console.log('<%= mArray %>') </script> <div id="mArray&qu ...

The whitespace issue stems from the div element __next-build-watcher generated by next js and usecontext

There's a notification bar at the bottom of my page that lets the user know when their email has been sent. This bar is generated using useContext in React/Next.js. To see the code, check out this Codebox link: Code However, I've noticed there ...

Assign object values only using Object.assign

I have two objects. One serves as the original source object, while the other is a deep copy of the source object with potentially different values. For example: { id: 123, people: [{ name: "Bob", age: 50 }, { name: "Alice", ...

My JSON data appears to be valid, yet I consistently encounter the error message "SyntaxError: JSON.parse: unexpected end of data at line 1"!

Help! I'm facing a problem while working on a game that requires initiating the game, registering the user, and obtaining game data from the server. When I try to start the game, nothing happens and I keep receiving an error message. I have verified t ...

Determine the number of keys within a JSON array

The issue lies not in the counting itself, but rather in setting the key-value pairs. Here's the snippet of code: <?php $jsonPacks = '{ "pack": [ { "container": 50, "layout": [ ...

Checking the existence of a user's email in Node.js

Hey there! I am new here and currently learning Node.js with Express. I'm trying to find a way to check if a user's email already exists in the database. Here is what I have so far: const emailExists = user.findOne({ email: req.body.email }); if ...

Three.js rendering malfunctioning after updating renderer

Update: Revised the question for a broader context. (Original here for reference) In my project, I am using Three.js WebGLRenderer to render a scene. I need to replace the existing renderer with a new WebGLRenderer by swapping out the canvas and then re-r ...

Add an array as a nested child within another array using node.js and JavaScript

Description: I execute a MySQL query to retrieve rows from a table > connection.query(q2,function(err,rows){...} Assuming the rows have a structure like {id:",,,", time:"..." etc:"cc"} For each row, I then query another table to fetch additional dat ...

I am unable to access the information from a .txt file using Ajax

I'm attempting to create a basic AJAX example, but I'm encountering issues getting it to function correctly. Below is the code I have: <script> function loadXMLDoc() { var xmlhttp; if (window.XMLhttpRequest) { ...

Navigating Through Objects

Currently, I am utilizing the Jquery Dropdown Plugin and ListJS Plugin for my project. The jQuery Dropdown Plugin features a hide event: $('.dropdown').on('hide', function(event, dropdownData) { }); Within this event, I am integratin ...

What are the best practices for utilizing ngrx entity selectors?

Currently, I am utilizing ngrx entity for managing my store. However, I seem to be facing an issue with selecting the store entities using selectors. Despite following the code example provided in this link: https://github.com/angular-university/angular-ng ...

Having trouble displaying a JSON response on an HTML page with AJAX

I've written an AJAX function that goes like this: function ajx(){ var ajaxRequest; // This variable makes Ajax possible! try{ // Works in Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Exp ...

Having trouble with Next.js Error: Attempting to access undefined properties (specifically 'call') and can't resolve it with try/catch method when using onClick event?

var mysql = require("mysql"); import React from "react"; export async function executeMySqlQuery(myQuery) { try { console.log("Running query..."); var connection = mysql.createConnection({ host: process.env.M ...

Preserve the parameter navigation stored within a flatlist and showcase it on a separate screen

I am looking to save a navigation parameter from a flatlist so that it can be displayed on another screen. This parameter is essentially a title stored in an array for the flatlist. react-native ScreenA <FlatList data={ this.state.FlatListItems } key ...

Validation using Joi allows for a field to be optional, but if it is included, it must be a positive integer

I am facing a challenge with a field in my JOI schema that I want to make optional, allowing for both undefined and null values. However, if a value is provided, it must be a positive integer. How can I accomplish this? So far, I have attempted the follow ...

Turn off the feature of map scrolling on OpenStreetMaps

Is there a way to prevent mouse interactions and scrolling in an open maps iframe? I have already tried adding the attribute scrollwheel="false" to no avail. Are there any CSS methods to achieve this? <iframe id= "mapsource" scrollwheel="false" src="ht ...

Styling images and text in CSS within a jQuery UI autocomplete widget

I am currently using an autocomplete widget that displays text along with images. The results I have right now are not meeting my requirements. I want to customize the appearance of my results so that the words 'test' and either 'Federico&a ...