如何使用angular在DOM中通过变量名访问对象的键

时间:2015-09-05 06:59:35

标签: javascript angularjs dom

我有一个控制器,它为范围添加一个名为comments

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

我想在特定ID上调用ng-repeat。以下方法无效。有什么想法吗?

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

所需的id被赋予外部div。但ng-repeat无效。

3 个答案:

答案 0 :(得分:0)

您应该使用过滤器来实现此功能,如下所示:

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

现在,写一个过滤器:

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

或者您可以使用更简单的方式

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

在你的控制器中:

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

答案 1 :(得分:0)

你可以这样做:

<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

答案 2 :(得分:0)

您应该使用bracket notation通过变量键访问属性:

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