2016-02-29 55 views
1

我得到一个项目列表,并循环这样的html代码。 (粘贴HTML代码段是不完整的,因为它的长条)从角度js列表中随机抽取一个项目

<div class="row" ng-repeat="recentuseraddress in timeline" > 
    <div class="address col-xs-12 col-sm-8 pull-left" > 
     <p><a href="<?php echo base_url(); ?>property/index/{{recentuseraddress.home_id}}"> 
       <img ng-src="<?php echo base_url(); ?>images/maps/{{recentuseraddress.propertyimg}}" height="50" width="50"> 
      </a> 
     <p>{{recentuseraddress.updated_time}}</p><br>{{recentuseraddress.recent_connect_address}} <span>{{recentuseraddress.recent_connect_postcode}}</span></p> 
    </div> 
    ...... 

你可以看到图像标签在HTML,基本上它打印在我的列表中的所有图像。

而现在在不同的地方同一个页面中,我需要从相同的角度JS只得到一个图像 {{recentuseraddress.propertyimg}} 随机

是否有任何直接角度js方法从列表中随机提取项目?

谢谢。

回答

0

用途:

$scope.randomImage= $scope.recentuseraddress.propertyimg[Math.floor(Math.random() * $scope.recentuseraddress.propertyimg.length)]; 

,并考虑:{{randomImage}}

+0

非常感谢你。只是看到了可能性,说清单是空的,没有任何可以随意选择的,那么有没有办法解决这个问题 – GUIR

+0

我在手机上。所以答案不会详细。您可以检查列表中是否存在空的条件,并为某个语句指定一个范围变量,并在句柄的帮助下显示。 –

+0

非常感谢。这有助于 – GUIR

0

你应该从你的控制器时间轴选择你的随机元素。 我模拟你的情况根据你的代码片段,并写下这个例子。

angular.module('app',[]) 
 
    .controller('mainController',function($scope){ 
 
    var timeline = [ 
 
    {home_id:1,propertyimg:'img1.jpg'}, 
 
    {home_id:2,propertyimg:'img2.jpg'}, 
 
    {home_id:3,propertyimg:'img3.jpg'} 
 
    ]; 
 
    $scope.timeline=timeline; 
 
    $scope.randomRecentUserAddress = timeline[Math.floor(Math.random() * timeline.length)]; 
 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js"></script> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body ng-app="app" ng-controller="mainController"> 
 
    <h1>Timeline</h1> 
 
    <pre> 
 
    {{timeline}} 
 
    </pre> 
 
    <h1>Random</h1> 
 
    <pre> 
 
    {{randomRecentUserAddress}} 
 
    </pre> 
 
    <img ng-src="{{randomRecentUserAddress.propertyimg}}"/> 
 
</body> 
 
</html>

+0

非常感谢。这也有帮助 – GUIR

相关问题