上一篇中我們已經知道如何使用 ng-repeat 來將陣列中的元素一一列出並產生畫面,但畢竟資料算都是不變的。所以今天筆者除了要教各位如何動態新增及刪除資料之外,還會多介紹一個新的宣告式語法(Directives Syntax) - ng-click 及 ng-dblclick。
這邊的範例就先以上一篇的內容為主:
1 2 3 4 5 6 | <div class="well span6" style="margin-top:20px;" ng-controller="FriendsCtrl"> <h3>共有 {{ friends.length }} 位朋友</h3> <div class="alert alert-info" ng-repeat="friend in friends" > {{ friend.name }} <span class="badge badge-important">{{ friend.age }} 歲</span> </div> </div> |
預覽時應該會看到每筆資料都一一排列出來,並顯示出目前共有幾位朋友:
然後我們在上面多加一些元素,讓我們可以用來新增新的 Person 物件使用:
1 2 3 4 5 6 7 8 9 10 | <div style="margin-bottom:20px;"> <label class="control-label" for="name">Name:</label> <input type="text" id="name" placeholder="Name" ng-model="pName"> <label class="control-label" for="age">Age:</label> <input type="number" id="age" placeholder="age" ng-model="pAge"> <br> <button class="btn">Add</button> </div> |
筆者這邊將輸入方塊一一綁定 pName 及 pAge 的 model。接著當 Add 鈕按下後,想要將該筆資料加到 friends 陣列中,所以來將按鈕加上 ng-click 語法吧:
1 | <button class="btn" ng-click="add()">Add</button> |
ㄟ~那個 add() 是那來的呢?別擔心,這是我們要自己加在 Controller 中的函式,所以打開我們的 js/controller.js,然後在 FriendsCtrl 中加上它吧:
1 2 3 4 5 6 | $scope.add = function(){ $scope.friends.push({ name: $scope.pName, age: $scope.pAge }); }; |
注意喔~要 add() 是屬於 $scope 的,所以要寫成 $scope.add 再指定函式。接著預覽並試著輸入看看吧:
有看到嗎?按下鈕後就會立即出現一筆新的資料,同時也會更新朋友數喔!
好啦!現在已經可以新增了,接下來要在 ng-repeat 區塊中多新增一個用來刪除資料用的按鈕:
1 2 3 4 | <div class="alert alert-info" ng-repeat="friend in friends" > <button type="button" class="close">×</button> {{ friend.name }} <span class="badge badge-important">{{ friend.age }} 歲</span> </div> |
不過預覽時會發現到是每筆資料都有個按鈕,所以我們得讓刪除的指定很明確的知道是要刪掉那一筆,所以這邊要多傳入一個 $index 當做參數才行:
1 | <button type="button" class="close" ng-click="remove($index);">×</button> |
一樣在 FriendsCtrl 中加上 remove():
1 2 3 | $scope.remove = function(index){ $scope.friends.splice(index, 1); }; |
這邊接到的 index 參數就是傳入的 $index。接著預覽並試著點擊 x 鈕試試吧:
筆者刪除了 2 筆,所以這邊會看到畫面中只有 3 筆資料,同時也是顯示只有 3 位朋友。是不是開始覺得 AngularJS 的雙向資料綁定(Two-way data-binding)的功能真的很簡單又方便呢!
啊不過我們雖然能加入新的資料,但輸入方塊內的值並沒有清空,這...就是這次的作業囉!