简体   繁体   中英

How to access a key of an object by its variable name in DOM using angular

I have a controller which adds to scope a variable called comments

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

I want to call the ng-repeat on a specific id. The following method is not working. Any ideas?

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

The desired id is given to the outer div. But ng-repeat is not working.

You should use a filter to achieve this functionality as follows:

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

Now, write a 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;
    }
})

Or you can use an easier way :

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

And in your controller:

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

You can do that with:

<div ng-app="myApp" ng-controller="dummy">
    <div class="commentsContainer" id="{{id}}">
        <div class="eachcomment" ng-repeat="(key, comment) in comments">
            <p ng-show="key === id">{{comment.content}}</p>
        </div>
    </div>
</div>

JS:

angular.module('myApp', [])
    .controller('dummy', ['$scope', function ($scope) {
    $scope.id = 0;
    $scope.comments = [{
        content: 'Hello'
    }, {
        content: 'World'
    }];

}]);

JSFiddle

You should use bracket notation to access property by variable key:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM