Ways to utilize the AngularJS ngShow command in order to display a certain element only if it is included in an array

In my quest to quickly display a list of all the authors linked to a particular publication, I've encountered an issue.

Everything runs smoothly when $scope.publications.authors holds a single value. However, problems arise when there are multiple values stored in an array, as shown below.

I understand that the conditional statement for the AngularJS ngShow directive is not suitable for arrays, but I'm struggling to find the correct approach.

HTML:

<div ng-repeat="person in persons" ng-show="person.firstName == publication.authors">{{person.firstName}}</div>

JS:

$scope.publications = [
{"title": "Research Paper",
 "authors": ["Bill", "George"]};

$scope.persons = [
{"firstName": "Bill",
 "lastName": "Smith"},
{"firstName": "George",
 "lastName": "Jones"},
{"firstName": "Mike",
 "lastName": "Thomas"};

Answer №1

If you want to properly display the data structure of publications, it's recommended to implement a nested repeater. Utilizing a function that takes in the current person and publication can help drive the presentation.

<div ng-repeat="publication in publications">{{publication.title}}
    <br/>
    <div ng-repeat="person in people" ng-show="show(person, publication)">{{person.firstName}}</div>
</div>

function ctrl($scope) {
    $scope.publications = [{
        "title": "Research Paper",
            "authors": ["Bill", "George"]
    }];

    $scope.people = [{
        "firstName": "Bill",
            "lastName": "Smith"
    }, {
        "firstName": "George",
            "lastName": "Jones"
    }, {
        "firstName": "Mike",
            "lastName": "Thomas"
    }];

    $scope.show = function (person, publication) {
        return publication.authors.indexOf(person.firstName) >= 0;
    }
}

Answer №2

To ensure the existence of an element in the persons array, create a function in your controller and invoke it using ng-show. Refer to the example in the following fiddle:

http://jsfiddle.net/ABC123/456/

Answer №3

In my opinion, the most effective approach would involve utilizing a method in your controller rather than attempting to loop through all the data within the DOM.

There are various methods you can use to achieve this. For example, if you prefer to have all the authors' names displayed on a single line, you could create a method that takes the authors as input and returns a string with all the names. You can then reference this method for the content of your div like so:

{{getAuthors(publication.authors)}}

Alternatively, you could create a method that returns an array of names and iterate through it using an ng-repeat directive, similar to the following:

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

Converting this Jquery function to vanilla Javascript

I'm currently encountering difficulties reworking this slideshow feature using Javascript. Due to certain project limitations, I am required to switch back to pure JS. document.querySelectorAll(".fadein img:not(:first-child)").forEach(function(element ...

Validation is not being enforced for the input field labeled as 'name' in the form

Can anyone assist me with a form validation issue I'm encountering while working on my project? The validation is functioning correctly for email and institution fields, but it seems to be ignoring the name field. Any suggestions or help would be grea ...

The communication between Angular and MVC controller fails to transfer the value, resulting in a null value being

My goal is to pass a value from Angular to my MVC Core controller in order to use it as a simple string in a repository function. However, I've encountered an issue where a null value is being passed to the MVC controller. I want to find a solution th ...

Can anyone recommend a regular expression that would target values ranging from 0.5 to 24?

I'm searching for a regex pattern that can identify numbers within the range of 0.5 to 24, excluding cases like 0,5 or 22,5. The current pattern I'm using is: /^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/ Despite having excluded the comma ,, ...

Error message: "React Component not identified"

I am following [this React tutorial][1] and facing an issue right from the start as my React components are not being identified. Here is a snippet of my code: import React from 'react'; import {BrowserRouter as Router, Route, Routes} from "react ...

Retrieve the array element that contains a date range matching the current time using JavaScript

I've been searching on Stack for an answer to my question, but I haven't found a solution yet. My issue is that I need to display only the object in my array where the current time falls within the specified date range defined by timeStart and ti ...

Running JavaScript code within a modal dialog box

Having trouble executing scripts inside a modal dialog? $(document).ready(function(){ $("#btn_transfer").click(function(){ // open Modal $('#transfer_stock').modal('show'); }); }); <script src="http://code.jquery.com/j ...

What is the measure of randomness created by Math.random?

I am trying to create a large random number without the need for cryptographic security. Therefore, I have opted not to use crypto.getRandomValues. Currently, my method of generating the random number is as follows: const random = length => Math. ...

Steps for assigning certain elements in an array to null and then repositioning them to the end of the array

Although I am aware that utilizing an ArrayList would make this task much simpler, I am limited to using arrays for now. Here is the method I have come up with: public boolean remove(String name) { int temp = 0; for (int i = 0; i < counter; i+ ...

Is there a way to have the even numbers in an array printed before the odd numbers?

Looking for a way to separate even and odd numbers into two arrays? This function will do just that, but with a twist - the evens array will be printed before the odds. var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13]; function customDivider(n ...

Displaying an alert when the text box contains a duplicate value

I have a set of input fields with various values that can be edited but must not be left empty (if left empty, display an alert). When I update a field with a new value, if that new value matches any of the other input field values, I want to display an al ...

Stacked column tooltip displaying an array of 3 values

I am working with a json code that looks like this: [[1385420403000,9.86,6.91],[1385506802000,11.89,6.57],[1385593203000,14.11,10.58],[1385679602000,9.1,8.9],[1385766003000,13.59,7.53],[1385852402000,10.68,6.69],[1385938803000,11.03,10.52],[1386025202000, ...

Check the File Format (not just the Extension) prior to Uploading

When uploading a file within an HTML form, you can validate the extension using JQuery's Validation plugin: <form enctype="multipart/form-data" id="form-id"> <input type="file" name="file-id" id="file-id" /> </form> To validate ...

Populating an array prior to AJAX transmission

I'm not a JavaScript expert, particularly when it comes to promises and callbacks. However, my goal is to have my JavaScript file perform the following tasks synchronously: 1. Create an array 2. Populate the array with all the necessary elements 3. Se ...

Is it possible to generate a JS error from Go web assembly?

I attempted js.Global().Call("throw", "yeet") However, I encountered panic: 1:1: expected operand, found 'type' [recovered] wasm_exec.f7bab17184626fa7f3ebe6c157d4026825842d39bfae444ef945e60ec7d3b0f1.js:51 panic: syscall/js ...

What is the best way to modify the background of my li element when it is clicked on?

I stumbled upon this article: Modifying Li Element Colors in HTML <ul> Using onclick Event It seems to address what I need, but I'm a little unsure of how to implement something similar in a rails app that also utilizes react/redux. Most of the ...

What is the best way to bring Axios into the main.js file in a Vue project?

Recently, I encountered an issue with using axios in my Vue project. An error message stating that 'axios' is not defined popped up when I attempted to use axios.get() in my Home.vue file. I'm wondering if the problem lies within my configur ...

Unleashing memory in C from the stack

Is there a method to release or minimize the memory allocated from the stack during runtime? For example: int num[10] = {1,2,3,4}; Is it possible to deallocate the 6*4 bytes (assuming int requires 4 bytes) during runtime? ...

What is the best method to override the CSS transition effect with JavaScript?

I am trying to implement a CSS transition where I need to reset the width of my box in advance every time my function is called. Simply setting the width of the box to zero makes the element shrink with animation, but I want to reset it without any animati ...

Add a new element to an array in a PHP file that will then output the modified

I am faced with a task involving a file that is structured like this: <?php return [ 'key1' => 'value1', 'key2' => 'value2', ... ]; The requirement is to add an additional array entry to this f ...