2016-02-17 10 views
-2

我如何創建這個div而我迭代json array重複「大」的div標籤並把格局化爲

我有我會在不同的縮略圖顯示在一排,我想有這樣的一個模板不同的數據:

for(var i = 0; i < jsonArray.length; i++) 
{ 
    <div class="row"> 
     <div class="col-sm-6 col-md-4"> 
      <div class="thumbnail"> 
       <img src="somesource" alt="sometext"/> 

       <div class="caption"> 
        <h3>jsonArray[i].title</h3> 
        <p>jsonArray[i].description</p> 
       </div> 
      </div> 
     </div> 
    </div> 
} 

如果有人知道如何做到這一點和框架提供這個,請幫助我。先謝謝你!

回答

1

您可以使用AngularJS的ng-repeat功能 只要看看我提供的示例代碼。

在你的情況,你的variabele jsonArray將不得不由$scope.items

分配或更換這裏有一個fiddle顯示工作的例子,或只是運行片段

var myApp = angular.module("example", []); 
 

 
myApp.controller("exampleController", ['$scope', example]); 
 

 
function example($scope) 
 
{ 
 
    $scope.items = [ 
 
    \t { 
 
    \t  title: "Title 1", 
 
      description: "This is a description for title 1" 
 
     }, 
 
     { 
 
    \t  title: "Title 2", 
 
      description: "This is a description for title 2" 
 
     }, 
 
     { 
 
    \t  title: "Title 3", 
 
      description :" This is a description for title 3" 
 
     } 
 
    ]; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="example"> 
 
    <div ng-controller="exampleController"> 
 
    <div class="row" ng-repeat="item in items"> 
 
     <div class="col-sm-6 col-md-4"> 
 
     <img src="#" alt="some image"/> 
 
     
 
     <div class="caption"> 
 
      <h3> 
 
      {{item.title}} 
 
      </h3> 
 
      <p> 
 
      {{item.description}} 
 
      </p> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

+0

謝謝您!我怎樣才能改變陣列?我需要一個可重複使用的函數來將數組放入函數中,無論何時更改數組中的數據,都應該循環 – mimu1011

+0

,$ scope將會接受更改並更新數據。您應該瞭解如何使用數組,也可能使用Angular和jQuery。嘗試一些培訓課程,只是練習。這些問題並不總是得到解答,但您至少應該嘗試自己編寫代碼。我們可以帶路,但不會解決所有問題。 – Jorrex

+0

,以及我的意思是「$範圍將提取更新並更新您的數據」。檢查這個小提琴並添加一個新的項目。我只是將它添加到我的當前數組中,它會自動添加到我的html中。 – Jorrex