Using AngularJS, what methods can I use with ng-show to filter through an array and identify specific values?

I have a model called Program, which has the following structure:

var ProgramSchema = new Schema({
  permissions: [{
      user: {
        type: Schema.ObjectId,
        ref: 'User'
      },
      roles: {
        type: [{
            type: String,
            enum: ['reader', 'editor', 'admin', 'requested']
          }]
      }
    }],
  type: {
    type: String,
    enum: ['public', 'private'],
    default: 'public',
    required: 'Type cannot be blank'
  }
});

When displaying a list of programs on a page, I want to show an icon if the currently authenticated user ($scope.authentication.user) is in the program.permissions.user with a role of reader, editor, or admin. I tried using ng-show but since programs.permissions is an array, it didn't work as expected. Any suggestions would be appreciated. Thank you!

Here is a sample data for a program:

{
    "_id" : ObjectId("55ab4acd24640cd55097c356"),
    "permissions" : [ 
        {
            "user" : ObjectId("55a897dfad783baa677e1326"),
            "roles" : [ 
                "reader"
            ]
        }, 
        {
            "user" : ObjectId("5563f65a84426d913ae8334e"),
            "roles" : [ 
                "editor"
            ]
        }
    ]
}

With some help, here is what I implemented:

I added a function call in my ng-show:

ng-show="userFollowedProgram(program)"

In my controller:

$scope.userFollowedProgram = function(program) {
  // Loop through permissions and check if user is present.
  for (var i = 0; i < program.permissions.length; i++) {
    if (program.permissions[i].user === $scope.authentication.user._id) {
      // Check if user has admin, editor, or reader role.
      if (program.permissions[i].roles.indexOf('admin') > -1 ||
          program.permissions[i].roles.indexOf('editor') > -1 ||
          program.permissions[i].roles.indexOf('reader') > -1) {
          return true;
        }
    }
  }
  return false;

};

Answer №1

Although it may not be the most visually appealing solution, one way to explicitly check for specific values is by using the || logical operator within the ng-show directive and applying the indexOf() method. To demonstrate this, I've provided a simple example below using a <span> element as an "icon." Feel free to adapt and incorporate this concept into your own code. Take a look at the following snippet...

<li ng-repeat="user in users">
    <span>{{ user.name }}</span>
    <span class="ico" 
          ng-show="user.roles.indexOf('reader') > -1 || user.roles.indexOf('editor') > -1 || user.roles.indexOf('admin') >-1">icon
    </span>
</li>

$scope.users = [{
        id: 1, name: 'bob', roles: ['reader', 'editor', 'admin']
    },{
        id: 2, name: 'jane', roles: ['reader']
    },{
        id: 3, name: 'chris', roles: ['editor']
    },{
        id: 4, name: 'susy', roles: ['requested'] // sorry susy
}];

JSFiddle Link - see a simple demo


Another approach worth considering involves testing for specific roles using regex patterns to determine a truthy value. This method may introduce additional complexity, so evaluate its relevance to your project requirements before implementing. Explore the following snippet for more insight...

<span class="ico" ng-show="isInRole(user)" >icon</span>

$scope.isInRole = function(user) {
    return /(reader|editor|admin)/.test(user.roles.join('|'));
}

JSFiddle Link - view a regex demonstration

Answer №2

After some investigation, I managed to solve the problem.

I implemented a function within my ng-show

ng-show="checkUserFollowedProgram(program)"

Here is the code snippet from my controller:

$scope.checkUserFollowedProgram = function(program) {
  for (var i = 0; i < program.permissions.length; i++) {
    if (program.permissions[i].user === $scope.authentication.user._id) {
      return true;
    }
  }
  return false;

};

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

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

Display Partial View in MVC 4 using ajax success callback

Issue: Unable to load view on ajax success. Situation: I have two cascaded dropdowns where the second dropdown's options are based on the selection of the first dropdown. Upon selecting an option in the second dropdown, I want to display a list of re ...

Jest identifies an open handle when working with an Express application

For quite some time now, I've been grappling with a particular issue. It all started when I was conducting basic integration tests using a MongoDB database. However, I've minimized the code to its simplest form. The only thing left running is a s ...

Having trouble accessing the URL route by typing it in directly within react-router?

Having some trouble getting dynamic routes to work with react router. Whenever I enter a URL like localhost:3000/5, I receive the error message "cannot GET /5". Here is how my router is configured: class App extends Component { render() { retu ...

Postman post request failing to insert Mongoose model keys

Recently, I've been experimenting with the post method below to generate new documents. However, when I submit a post request in Postman (for example http://localhost:3000/api/posts?title=HeaderThree), a new document is indeed created, but unfortunate ...

Creating an extra dialogue box when a button is clicked in React

Having an issue with displaying a loading screen pop-up. I have an imported component named LoadingDialog that should render when the state property "loading" is true. When a user clicks a button on the current component, it triggers an API call that chang ...

Conceal the results of echoing json_encode

One dilemma I encountered was passing an array from PHP to JavaScript using json_encode and ajax. The only method that seemed available was to use echo json_encode($var) This approach printed out the contents of $var on the page due to the echo statement ...

Is it appropriate to delete the comma in the Ghost Handlebars Template?

While navigating through the tags, I unexpectedly encountered a comma. This could potentially have an unwanted impact. I attempted to remove the comma, but is there a specific method to eliminate it completely? I referred to the Ghost blog Document for gui ...

ReactJS: Issue encountered when trying to retrieve the selected value - 'value' property of null is undefined

My objective is to retrieve the value of the selected <option> from the <select> element, but I am encountering an error in my current code that reads: cannot read property 'value' of null. I have tried various methods found onlin ...

React - Triggered a higher number of hooks compared to the prior render (potentially based on a condition

I have encountered this error numerous times: The number of hooks rendered is higher than during the previous render. From my understanding, this issue is related to an early return statement. I am currently developing a library for our company where I w ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...

Tips on displaying tooltips on multiple graphs in Highcharts using Vue 3

I am currently utilizing vue3-highcharts in conjunction with Highcharts. My goal is to replicate a similar functionality as shown in this example: https://codepen.io/lzl124631x/pen/KLEdby?editors=1010. However, I am unsure about the correct syntax for impl ...

Utilizing an Angular Directive to set up various jQuery plugins simultaneously

As a newcomer to Angular, I must ask for patience with any lack of knowledge evident in this post. Specifics: In my project, I am utilizing CodeIgniter alongside Angular.js, and I am grappling with the process of initializing multiple plugins within my a ...

The lack of definition for the props value poses an issue in React.js Hooks

I'm currently developing a notepad web application that utilizes React Hooks for managing state variables. In order to fetch data from an API, I am using the axios library. The retrieved data consists of objects with fields such as _id, title, status, ...

Responsive Bootstrap table unable to expand div upon clicking

My bootstrap responsive table has a unique functionality that allows specific divs to expand and collapse upon button click. While this feature works seamlessly in desktop view, it encounters issues on mobile devices. CSS .expandClass[aria-expanded=true] ...

Encountered a problem while rendering the app: [TypeError: Unable to assign a value to the property 'content' since it is undefined]. Implementing Express with

My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...

Ways to determine if a browser is currently loading a fresh webpage

I'm experiencing an issue with my web app where the 'safety' code triggers a page reload if the server (Socket.IO) connection becomes silent for more than 5 seconds, often due to customer site firewall or broken-proxy issues. Although the S ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

Is there a way to implement the focus function and invoke a JavaScript function within an ASP.NET application?

Whenever I click on the textbox, a function is called. The code for that is: onclick="GetColorBack()" However, the GetColorBack function is only called when clicking on the textbox. If I navigate using the TAB key, it does not trigger the function. Is t ...

Ways to categorize JSON information

Is it possible to group JSON data by group_name? JSON : [ {"fullname":"fffffffff","email":"sss@gg","mobile":"3333333333","designation":"ggg","group_name":"engineers"}, {"fullname":"ddddddddddd","email":"sssg@gg","mobile":"3333333333","designation":"ffff ...