【问题标题】:How to access a key of an object by its variable name in DOM using angular如何使用 Angular 通过 DOM 中的变量名访问对象的键
【发布时间】:2015-12-01 08:12:09
【问题描述】:

我有一个控制器,它在作用域中添加了一个名为 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 不起作用。

【问题讨论】:

    标签: javascript angularjs dom


    【解决方案1】:

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

    <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;
    }
    

    【讨论】:

    • 但这给了我以 ID 作为键的对象。如何访问与给定 ID 链接的内容。我事先不知道 ID。
    • 当您的 ng-repeat 运行时,您的 $scope.id 设置正确吗?
    • 这是在另一个 ng-repeat 中运行。所以我正在使用 ng-init 为外部重复中的每个元素初始化一个 id。
    • 请创建一个插件
    【解决方案2】:

    你可以这样做:

    <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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2022-07-28
        • 2019-01-26
        • 2018-11-08
        • 2019-02-12
        • 2014-04-25
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多