在另一个ng-repeat中使用ng-repeat时遇到问题

时间:2018-09-18 14:46:25

标签: angularjs

<div ng-repeat="x in allMessages">
     <div class="card testimonial-card btn-rounded p-1 mb-2">
        <strong>@{{x.sender_username}}</strong>
        <p>{{x.messages}}</p>
        <div ng-repeat="file in x.files">
            {{file}}
        </div>
    </div>
</div>   

根据上面的代码,除了第二个ng-repeat之外,其他所有东西都运行良好。我从JavaScript(一个数组)中获取了allMessages(这是一个数组),它还包含另一个数组(文件),如何获取allMessages中每个数据显示的文件的全部内容?

1 个答案:

答案 0 :(得分:0)

为使代码正常工作,对象allMessages.files必须是一个数组。 ng-repeat仅适用于集合。这意味着您的allMessages对象将如下所示:

[{
    sender_username: "",
    messages: "",
    files: [
        "",
        ""
    ]
}]

请参见下面的工作片段:

angular.module('testApp', [])
  .controller('TestAppController', function($scope) {
    
    $scope.allMessages = [
      {
        sender_username: "John.Doe",
        messages: "Sample Message",
        files: [
        "file 1",
        "file 2"
        ]
      },
      {
        sender_username: "Janet.Doe",
        messages: "Hi! Whats up?",
        files: [
        "Cinnamon.jpg",
        "Black_tea.png"
        ]
      }
    ];
    
  });
.card{
  border: 1px solid grey;
  margin: 10px
}

div.card div{
  margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>


</script>
<body ng-app="testApp" ng-controller="TestAppController">
<div ng-repeat="x in allMessages">
     <div class="card testimonial-card btn-rounded p-1 mb-2">
        <strong>@{{x.sender_username}}</strong>
        <p>{{x.messages}}</p>
        <div ng-repeat="file in x.files">
            {{file}}
        </div>
    </div>
</div>  
</body>

相关问题