萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

AngularJS + HTML5 打造動態圖片牆:可增刪、響應式網格佈局實戰

結合 AngularJS 雙向綁定與 Bootstrap 響應式網格,快速構建一個支援動態增減、每行最多四欄的圖片牆/清單牆介面。資料模型採用巢狀陣列(標題 + 明細項目),配合 ng-repeat 即時渲染,無需手動操作 DOM,極大降低維護複雜度。

完整單頁原始碼

<!DOCTYPE html>
<html ng-app="app">
<head>
  <meta charset="UTF-8">
  <title>動態圖片牆 Demo</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <script src="js/angular.min.js"></script>
  <style> ul{list-style:none;} </style>
</head>
<body ng-controller="myCtrl">
  <div class="row">
    <div class="col-sm-12">
      <h3 class="label-info">{{title}}</h3>
      <button class="btn btn-primary" ng-click="addList()">新增清單</button>
    </div>
  </div>

  <div class="row">
    <ul>
      <li ng-repeat="group in tasklist.all">
        <div class="col-xs-6 col-sm-4 col-md-3">
          <div class="thumbnail">
            <input type="text" ng-model="group.title" style="width:100%" placeholder="清單標題">
            <ul>
              <li ng-repeat="item in group.list">
                <input type="checkbox" ng-model="item.done">
                <input type="text" ng-model="item.item" placeholder="明細內容">
                <button class="btn btn-xs btn-danger" ng-click="removeItem(group, $index)">刪除</button>
              </li>
              <li><button class="btn btn-xs btn-success" ng-click="addItem(group)">+ 新增明細</button></li>
            </ul>
          </div>
        </div>
        <button class="btn btn-xs btn-warning" ng-click="removeGroup($index)">刪除整組</button>
      </li>
    </ul>
  </div>

  <script>
    var app = angular.module('app', []);
    var myTaskList = { all: [
      {title:"第一組", list:[{done:false,item:"項目1"},{done:false,item:"項目2"}]},
      {title:"第二組", list:[{done:false,item:"項目A"},{done:false,item:"項目B"}]}
    ]};
    app.controller('myCtrl', function($scope){
      $scope.title = "響應式圖片牆 / 清單牆示範";
      $scope.tasklist = myTaskList;
      $scope.addList = function(){ $scope.tasklist.all.push({title:"新清單", list:[]}); };
      $scope.removeGroup = function(idx){ $scope.tasklist.all.splice(idx,1); };
      $scope.addItem = function(g){ g.list.push({done:false,item:""}); };
      $scope.removeItem = function(g, idx){ g.list.splice(idx,1); };
    });
  </script>
</body>
</html>

關鍵技術點

  1. Bootstrap 網格系統:col-xs-6 col-sm-4 col-md-3 實現超小螢幕2欄、小螢幕3欄、中螢幕以上4欄自動斷點。
  2. 巢狀 ng-repeat:外層迴圈群組,內層迴圈明細,配合 ng-model 雙向綁定輸入框與勾選框。
  3. 控制器方法封裝增刪:addList/removeGroup/addItem/removeItem 直接操作模型陣列,視圖自動同步。
  4. 擴充性:只需在模型物件加入 imgUrl 欄位並將輸入框改為 <img ng-src="..."> 即可轉型為真正的圖片牆。

進階優化方向

  • 加入 ng-animate 或 Animate.css 讓增刪項目擁有過渡動畫。
  • 使用 track by $index 或唯一 id 提升大量清單渲染效能。
  • 整合 angular-drag-and-drop 實現拖曳排序群組與明細。
  • 後端對接:將 tasklist.all 透過 $http 同步至 RESTful API,實現多裝置同步。

此範例展示了 AngularJS 在「資料驅動視圖」範式下的簡潔威力,適合快速原型、後台管理介面、行動端混合應用等場景。

copyright © 萬盛學電腦網 all rights reserved