【问题标题】:How to create a nested ng-repeat from nested JSON array data on button click如何在按钮单击时从嵌套的 JSON 数组数据创建嵌套的 ng-repeat
【发布时间】:2014-12-03 19:47:07
【问题描述】:

以下面的JSON 为例,假设我已将此数据设置为等于$scope.people

[
    {
        "personId": 1,
        "name": "Thomas",
        "age": 39
        "friends": [
            {
                "friendId": 1,
                "nickName": "Lefty"
            },
            {
                "friendId": 2,
                "nickName": "Morty"
            },
            {
                "friendId": 3,
                "nickName": "Gomer"
            }
        ]
    },
    {
        "personId": 2,
        "name": "George",
        "age": 27,
        "friends": [
            {
                "friendId": 1,
                "nickName": "Tommy"
            },
            {
                "friendId": 2,
                "nickName": "Bobby"
            },
            {
                "friendId": 3,
                "nickName": "Joe"
            }
        ]
    }
]

我正在为每个人动态创建按钮。

<div class="form-group" data-ng-repeat="person in people">
    <button type="button" class="btn btn-default form-control"
        data-ng-click="friends(person.personId)">
            {{person.name}}
    </button>
</div>

我想弄清楚的是如何根据单击的按钮将对象数据加载到引导面板(参见下面的 HTML):

<div class="panel panel-primary" data-ng-hide="!friends">
    <div class="panel-heading">
        <h4 class="panel-title">{{person.name}}<span class="pull-right">{{person.age}}</span></h4>
    </div>
    <div class="panel-body">
        <table class="table table-striped">
            <tr data-ng-repeat="friend in person.friends">
                <td>{{$index + 1}}</td>
                <td>{{friend.nickName}}</td>
            </tr>
        </table>
    </div>
</div>

我在想,在我的控制器上,我设置了一个 $scope 变量 = 朋友数组 ($scope.friends),但我不确定如何根据 personId 来做到这一点。

【问题讨论】:

    标签: javascript jquery arrays angularjs


    【解决方案1】:

    您需要创建一个 $scope 变量来保存 selectedPerson 并在单击按钮时将正确的人分配给所选人员

    $scope.SelectMe = function (p) {
            $scope.selectedPerson = p;
        }
    

    然后您可以在填充面板时引用 selectedPerson

    我为你准备了一个快速的小提琴。 http://jsfiddle.net/cseignc/wt8w01b4/

    如果这是您需要的,请告诉我。

    【讨论】:

    • 是的,但他想用 id 来做,不是吗?
    【解决方案2】:

    您可以使用字典而不是数组: 使用 underscore.js 中的 indexBy() 函数 http://underscorejs.org/#indexBy

    然后你可以做类似的事情

    $scope.peopleById = _.indexBy(people, "personId");
    

    在html文件中

    <tr data-ng-repeat="(id, friend) in person.friends">
    <!-- here you can do peopleById[id] -->
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多