2016-02-29 66 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

相關問題