1. 程式人生 > >Angular JS 之對錶格進行操作

Angular JS 之對錶格進行操作

使用 Angular 對錶格進行操作

1、匯入所需要的包

2、向表格中新增資料

3、設定事件對錶格進行操作

示例圖:

(如圖,點選刪除按鈕刪除表格中的一行)

程式碼如下:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>AngularJS之對錶格進行操作</title>
		
		<!--
			導包
		-->
		<script src="js/angular.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/jquery-3.2.1.min.js" type="text/javascript" charset="utf-8"></script>

	</head>

	<!--
		AngularJS對應的指令
	-->
	<body ng-app="myApp" ng-controller="myCtrl">

		<table border="1px" cellspacing="0" cellpadding="1">

			<tr>
				<td>姓名</td>
				<td>性別</td>
				<td>刪除</td>
			</tr>

			<tr ng-repeat="people in person">
				<td>{{people.name}}</td>
				<td>{{people.sex}}</td>
				<td><input type="button" value="刪除" ng-click="dele($index)" /></td>
			</tr>

		</table>

		<script type="text/javascript">
			var modul = angular.module("myApp", []);

			modul.controller("myCtrl", function($scope) {

				//將陣列初始化出來
				$scope.person = [{
					"name": "張三",
					"sex": "男"
				}, {
					"name": "李四",
					"sex": "女"
				}, {
					"name": "趙六",
					"sex": "男"
				}];

				//刪除按鈕的點選事件
				$scope.dele = function($index) {

					/**
					 * 因為Angular是雙向繫結的,所以只要視圖裡面的資料改變,檢視就會自己改變
					 * 
					 * 在這裡我們只需要將數組裡面的資料刪除就可以了
					 */
					$scope.person.splice($index, 1);

				}

			});
		</script>

	</body>

</html>