Exploring the process of accessing an object's key in the DOM through Angular by utilizing its variable name

Within my controller, I have a function that adds a variable called comments to the scope.

$scope.showComments = function(id){
    dataService.getComments(id).then(function(data){
        $scope.comments[id] = data.comments;
        console.log($scope.comments);
    });
}

I am trying to use ng-repeat on a specific id, but so far it's not functioning as expected. Any suggestions for fixing this issue?

<div class="commentsContainer" id="{{id}}">
    <div class="eachcomment" ng-repeat="comment in comments.{{id}}">
        <p>{{comment.content}}
    </div>
</div>

The correct id is being passed to the outer div, however, the ng-repeat directive is not working properly.

Answer №1

To achieve this functionality, it is recommended to utilize a filter in the following manner:

<div class="eachcomment" ng-repeat="comment in comments | filterId: id">
    <p>{{comment.content}}
</div>

To create the filter:

app.filter('filterId', function(){
    return function(collection, id) {
        var output = [];
        angular.forEach(collection, function(item) {
            if(item.id == id) {
                output.push(item)
            }
        })
        return output;
    }
})

Alternatively, you can opt for a more straightforward approach:

<div class="eachcomment" ng-repeat="comment in comments | filter: checkId">
        <p>{{comment.content}}
    </div>

In your controller:

$scope.checkId = function(item) {
    if($scope.id == item.id) {
        return true;
    }
    return false;
}

Answer №2

If you want to achieve this, use the following code snippet:

<div ng-app="myApp" ng-controller="example">
    <div class="messagesContainer" id="{{id}}">
        <div class="eachmessage" ng-repeat="(identifier, message) in messages">
            <p ng-show="identifier === id">{{message.content}}</p>
        </div>
    </div>
</div>

JavaScript:

angular.module('myApp', [])
    .controller('example', ['$scope', function ($scope) {
    $scope.id = 0;
    $scope.messages = [{
        content: 'Good Morning'
    }, {
        content: 'Good Evening'
    }];

}]);

JSFiddle Link

Answer №3

When accessing a property by a variable key, it is recommended to use bracket notation:

<div class="commentsContainer" id="{{id}}">
    <div class="eachcomment" ng-repeat="comment in comments[id]">
        <p>{{comment.content}}
    </div>
</div>

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

Some parts of the controller exhibit undefined values when accessing the Angular variable, while in other areas, it returns the expected value

I am currently working on a controller where I receive an array of values from a service. Upon receiving the values, I assign the value of a variable as the first element of that array and then perform a console.log to verify the value, which is returned c ...

Identifying the absence of a character at the end of the last line in Node.js to detect

Currently, I am processing data line by line from a buffer. Within the buffer, the data is structured as follows: name,email,phn test1,<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47332234337607223f262a372b226924282a">[em ...

Setting Up Date Selection Tool for Storing Data in MySQL Database

I've encountered an issue where when trying to post values from text boxes populated by date pickers to my database, the value 1970-01-01 is posted instead. I've researched and can't seem to pinpoint where the problem lies. Below are the inp ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

Guide on sending a JSON response from a POST request in JavaScript

After creating an API in Django that provides a JSON response based on a variable entered in the URL, I encountered a challenge with fetching and displaying this data using JavaScript. For instance, consider this URL: A sample of the JSON response looks ...

The ngResource module failed to instantiate within the angular/browserify environment

Recently, I decided to test out browserify in conjunction with Angular. After adding ng-resource to my project using the following command: npm install --save ng-resource I attempted to load it into my code like this: require('angular'); requi ...

looking to switch out the iframe when clicked

Whenever a user clicks on the getPrice button again and selects different input, I want to replace the iframe. Despite trying multiple approaches in my code, nothing seems to work out. Using document.body.appendChild() every time is not an option for me. ...

Modify the color of the header on Material-UI Date Picker

I recently integrated a Material-UI Date Picker into my React Single Page Application and now I'm facing an issue with changing the header color. I attempted to modify it using the muiTheme palette property, but unfortunately, the header color remains ...

What is the best way to alternate $httpBackend when[method] declarations in unit tests to handle multiple requests?

When conducting my testing, I set up the model data and mock the response: beforeEach(function(){ var re = new RegExp(/^http\:\/\/.+?\/users-online\/(.+)$/); $httpBackend.whenGET(re).respond({id:12345, usersOnline:5000}); }) ...

Ways to effortlessly activate an angular directive once the page has been fully loaded

I am facing an issue with a print directive that is triggered by the print="id" attribute within an <a></a> element. The button is contained in a modal that remains hidden from the user. I want the directive to execute as soon as the modal is l ...

The proper way to cancel useEffect's Async in TypeScript

I'm facing an issue with this straightforward example: useEffect(() => { axios.get(...).then(...).catch(...) }, [props.foo]) warning: can't perform a react state update on an unmounted component After some investigation, I found this ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...

Is there a way to select a checkbox in the main frame while in the $(document).ready of an embedded iframe?

I attempted this approach: $(document).ready(function(){ $(parent.top).find('.IAgreeCheckBox:first').prop("checked", true); }); but unfortunately, it did not work as expected. ...

What is the process for creating a register command using discord.js and MongoDB Atlas?

How can I save my Discord member data using a register command? Please provide assistance! bot.js client.on("message", msg => { if (msg.content === "!register, ign:<input from member>, level:<input from member>"){ ...

The onchange event is failing to trigger any JavaScript function

I am facing an issue where the onchange event of a dropdown menu is not triggering at all. I even tried redirecting it to a simple JavaScript function for testing purposes, but that didn't work either. I'm struggling to find a solution. Below is ...

A brief overview of handling currency in AngularJS

I currently display the price as <label>{{cart.on_sale_price|currency:"$"}}</label>, which gives me $ Now, within my JSON response, I have set cart.currency="INR" My question is: Is it possible to dynamically display the currency like this: ...

Error: Exceeded the maximum call stack size - What causes this and how can it be prevented?

I am currently utilizing standard JavaScript. As the title implies, I am encountering a RangeError and I'm unsure of how to prevent it. The issue at hand is that I shouldn't be receiving this error, and in reality, if I refresh the page there&ap ...

Issue with form validation causing state value to remain stagnant

Giving my code a closer look, here is a snippet in HTML: <input type="text" name="email" id="email" autoComplete="email" onChange={(e) => {validateField(e.target)}} className="mt-1 ...

Struggling with loading external scripts within background.js in Chrome extensions?

I am facing an issue with my chrome extension. I am unable to call an external script, specifically the ethereum script (web3.min.js), from within my background.js file. The error message I receive is: Uncaught EvalError: Refused to evaluate a string ...

remove a row from a table within a Firestore database

I'm currently working on implementing a button to delete a specific row in my table from the Firebase database, but I'm uncertain about how to achieve this using a button function. My code is written in JavaScript and utilizes Firestore. Below i ...