ng-repeat获取数组的长度并绑定数组的最后一个值

时间:2017-06-06 09:22:02

标签: angularjs arrays angularjs-ng-repeat ng-maxlength

$scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }

使用ng-repeat

进行结合数据
 <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>  
    </div>
     </div>

结果是     Apple - 3500 三星 - 4000 诺基亚 - 1500 诺基亚 - 7000

这里的每件事都好。但是我想要的意思是,诺基亚有两个阵列,所以我必须得到第一个阵列的名字和第二阵列的价格喜欢,

诺基亚 - 7000,

而且我还需要学生阵列的长度。

2 个答案:

答案 0 :(得分:1)

首先,您应该更改 JSON 以获得结果。

将JSON更改为以下:

$scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

请在代码下方运行

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

 <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>  
    </div>
     </div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

});
</script>

</body>
</html>

我使用 ng-if="$last" 来获取数组中的最后一个值

Here is a working DEMO

答案 1 :(得分:0)

如果您只希望Name: Nokia使用此功能,请执行以下操作:

<div ng-repeat="A in As.Student">
 <span ng-if="A.Name!=='Nokia'">{{A.Name}}-{{A.Price}}</span>  
 <span ng-if="A.Name==='Nokia' && $last">{{A.Name}}-{{A.Price}}</span>  
</div>

并且你只希望每个数组都有last element

然后:

 <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>  
 </div>