Show Angular if it is in the array

Presently, I have an ng-repeat function to display comments on articles. It is structured like this:

<div ng-repeat="comment in comments">
          <li class="item" ng-class-even="'even'">
            <div class="row">
              <div class="col">
                <i class="icon ion-person"></i> {{ comment.user.first_name }} {{ comment.user.last_name }}
                <i class="icon ion-record"></i> {{ comment.created_at }}
              </div>
              
              <div ng-show="hasRole(comment.user)" class="col right">
                <i class="icon ion-record admin"></i> Admin
              </div>
            </div>
            
            <div class="row">
              <div class="col">
                <p>{{ comment.text }}</p>
              </div>
            </div>
          </li>
        </div>

I am working on displaying the following content only for users with admin privileges:

<div ng-show="hasRole(comment.user)" class="col right">
                <i class="icon ion-record admin"></i> Admin
              </div>

To achieve this, I followed suggestions from this article.

In order to make it work, I created a function in my controller as shown below:

 $scope.hasRole = function(roleName) {
    return $scope.comments.user.roles.indexOf(roleName) >= 0;
  }

However, each time I run this function, it returns -1 even when the user has admin rights. Here is a snippet of my data structure:

1:Object
    $$hashKey: "object:28"
    article_id:"2"
    created_at:"2016-05-12 12:19:05"
    id:6
    text:"someCommentText"
    updated_at:null
    user:Object
        active:"1"
        created_at:null
        first_name:"admin"
        id:1
        last_name:"admin"
        roles:Array[1]
            0:Object
            created_at:null
            id:1
            name:"Admin"
            parent_id:null
            pivot:Object
            slug:"admin"

Answer №1

Insert the following code snippet into your HTML:

<div ng-show="hasAdminRole(comment.user.roles)" class="col right">
    <i class="icon ion-record admin"></i> Admin
</div>

This function is used to check if the user has an admin role:

$scope.hasAdminRole = function(roles) {
    var isAdmin = false;
    for(var i = 0; i < roles.length; i++) {
        if (roles[i].name == 'Admin') {
            isAdmin = true;
            break;
        }
    }

    return isAdmin;
}

Answer №2

It's possible that there is an issue right here on this particular line.

var indexOfRole = $scope.comments.indexOf(user.roles);

The goal here is to determine if the user's list of roles can be found within the comments array.

You might want to simply check within the actual user.roles array to see if there is an Admin role present. Perhaps try something like this:

$scope.hasRole = function(user) {
  for (var i = 0; i < user.roles.length; i++) {
    if (user.roles[i].slug === 'admin') { return true; }
  }
  return false
}

Answer №3

The reason for this is that the provided link contains an array, and only arrays allow you to fetch the index of its elements since it's an object.

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

Understanding Angular Terms: The Hash Object

While going through the AngularJS developer guidelines, I found myself a bit confused. Despite having experience in JavaScript, I couldn't grasp some parts of the documentation. Specifically, I was puzzled about the concept of a hash object. I though ...

Embrace the presence of null values on the client side

When utilizing the code below, I can determine the location of logged-in users. However, there are some users who do not have a specific location assigned. For example, Administrators are common for all locations. In such cases, how can I set it so that ...

Searching for values within an array of objects by iterating through nested arrays to apply a filter

Having trouble returning the testcaseid from an array to this.filteredArray Able to fetch header value and all values of the array when the search word is empty. Seeking assistance with iterating through the testcaseid and header on the search input fiel ...

Invoking res.download() in the Express framework

It's puzzling why this issue is occurring, and it's quite frustrating. I was expecting the file to be downloaded in line with the guidelines provided in the Express documentation. Below is the code snippet I am using: //within React (App.js) ...

What is the method utilized by Redux to store data?

I am currently developing a small application to enhance my understanding of how to utilize redux. Based on my research, redux allows you to store and update data within the store. In my application, I have implemented an HTML form with two text inputs. Up ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

What is the proper method for running a script using the Selenium JavascriptExecutor?

On my test.html page, I've included the following code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> </head> <body> ...

Could someone provide a detailed explanation of exhaustMap in the context of Angular using rxjs?

import { HttpHandler, HttpInterceptor, HttpParams, HttpRequest, } from '@angular/common/http'; import { Injectable } from '@core/services/auth.service'; import { exhaustMap, take } from 'rxjs/operators'; import { Authe ...

Guide on exporting a submodule within a TypeScript package

My aspiration is to develop a Typescript library that emulates the structure of popular libraries like RxJS and Angular Material, which are divided into submodules. RxJS and Angular exhibit a way to import features using syntax like this: // RxJS import ...

Tips for implementing event handlers on dynamically generated li elements in VueJS

Creating multiple ul elements using v-for in the following way <div v-for="item in info"> <ul> <li><a>{{item.number}}</a></li> <li><a>{{item.alphabet}}</a></li> </ul> </div&g ...

What method can be employed to eliminate choice selection lacking any value?

Currently, I am encountering difficulties in my attempt to remove or hide the first option value from a ransack code. Would you be able to assist me in addressing this concern? Here is the HTML CODE that I am working with: <select id="q_c_0_a_0_name" ...

Utilizing ion-list to showcase the subcategories of the chosen element

I'm currently developing an app that involves displaying a list of items. When a user selects an item, they are redirected to another page where a new set of items is listed with checkboxes for further actions. While I am able to select an item from t ...

Enhancing the menu/navigation bar with individual AJAX loaders

I have chosen the Vivant Designs theme for our website, which can be found at What I am looking to achieve is an ajax loader that will appear next to the link or tab when a user clicks on a link within the drilldown menu located on the left side. The cont ...

Trouble with disabling default actions and transferring text

When the user clicks on loginAccount, the intention is to extract the text from the element with the id input-1 and assign it to username. This same process should occur for password, followed by form submission. However, despite using e.preventDefault() ...

The next-auth/discord callbacks do not make any changes to the data

Currently, I am utilizing the next-auth/discord and facing an issue with the session callback not setting the user id to the session property as expected. [...nextauth].js import NextAuth from "next-auth/next"; import DiscordProvider from " ...

Utilizing Backbone script for fetching data from an external JSON source

I am seeking assistance on how to utilize a Backbone script to display data from a JSON file. Here is the structure of the HTML Page: <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</tit ...

Avoid displaying pop-up repeatedly (using current library)

I am currently customizing a Shopify theme that includes its own popup settings. I have created a new popup for my website that prompts visitors to choose their preferred language upon arrival. Everything seems to be working fine up to this point, but the ...

Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy... Essentially, within this object... my goal is to locate the pageviews node, but only if it has an array of data... Here's an example of the data: data = [ ...

Navigating through a multistep form in AngularJS using UI Router and arrow keys for seamless movement

Is there a way to navigate to the next or previous form step using arrow keys in AngularJS UI Router? The code provided below is currently allowing navigation with previous and next buttons. .config(function($stateProvider, $urlRouterProvider) { $stat ...

Rotating an HTML caret using CSS does not pivot from the center point

Is there a way to adjust my simple caret rotation to make it rotate from the center? What changes should I make? const Wrap = styled.div` width: 100px; background: grey; span { display: block; transform: ${(props) => (props.isOpen ? " ...