一個AngularJS的小栗子 - todoList

這是一個學習AngularJS中的一個栗子,todoList,把學習過程記錄下來,便於之後練習。javascript

首先,咱們來建立html,爲了美化我使用了BootStrap,代碼以下:css

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>todoList</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css">
  </head>
  <body style="padding: 10px;">
    <div class="input-group">
      <input type="text" class="form-control">
      <span class="input-group-btn">
        <button class="btn btn-default">提交</button>
      </span>
    </div>
    <h4>任務列表</h4>
    <ul class="list-group">
      <li class="list-group-item">1</li>
      <li class="list-group-item">2</li>
      <li class="list-group-item">3</li>
    </ul>
  </body>
  <script src="http://cdn.bootcss.com/angular.js/1.5.5/angular.min.js"></script>
  <script src="app.js"></script>
</html>

爲了養成良好的習慣,我吧AngularJS的代碼寫在app.js文件裏html

咱們先在html裏使用ng-app來聲明AngularJS的管理邊界,並指定這個模塊的名稱todoListjava

<html lang="zh-CN" ng-app="todoList">

app.js:git

'use strict';

angular.module('todoList', [])     // 使用angular的module方法聲明模塊todoList
.controller('TaskCtrl', function($scope){    //生成控制器TaskCtrl
  $scope.task = '';            //在$scope上定義變量task
  $scope.tasks = [];           //在$scope上定義空數組變量tasks
})

接着,咱們在body標籤中加入定義的控制器TaskCtrlgithub

<body ng-controller="TaskCtrl">

input標籤中使用ng-model指令綁定輸入,也就是把輸入與變量task綁定起來bootstrap

<input type="text" class="form-control" ng-model="task">

如今咱們爲提交按鈕添加一個添加列表事件,在button裏使用ng-click添加事件數組

<button class="btn btn-default" ng-click="addItem()">提交</button>

在app.js裏響應這個事件app

'use strict';

angular.module('todoList', [])     // 使用angular的module方法聲明模塊todoList
.controller('TaskCtrl', function($scope){    //生成控制器TaskCtrl
  $scope.task = '';            //在$scope上定義變量task
  $scope.tasks = [];           //在$scope上定義空數組變量tasks
  $scope.addItem = function() {
    $scope.tasks.push($scope.task);  
  }
})

最後咱們在html裏使用指令ng-repeat來遍歷用戶輸入,並把他們顯示到下面的列表當中ide

<ul class="list-group">
  <li class="list-group-item" ng-repeat="item in tasks track by $index">
    {{item}}
  </li>
</ul>

ng-repeat指令裏的內容表示,使用項目下標來遍歷並輸入列表項

至此咱們就完成了一個簡單的Angular應用,todoList,可是有兩個問題咱們來完善下,一是項目列表能夠添加一個刪除,還有就是那個<h4>任務列表</h4>,能夠在沒有列表項時將其隱藏

咱們先來隱藏這個<h4>任務列表</h4>,有兩種方式,分別使用ng-hideng-if均可以實現

<h4 ng-hide="tasks.length==0">任務列表</h4>
// 列表項數組長度爲0時,將此標籤隱藏
<h4 ng-if="tasks.length > 0">任務列表</h4>
// 列表項數組長度大於0時才顯示這個標籤

在實際應用中推薦使用ng-if指令,由於這個指令不會在DOM中建立對應的標籤,而ng-hide無論對應的標籤是否隱藏或顯示,都會建立。

而另一個,在列表項中建立一個刪除

<ul class="list-group">
  <li class="list-group-item" ng-repeat="item in tasks track by $index">
    {{item}} <a ng-click="tasks.splice($index,1)">刪除</a>
  </li>
</ul>

這個練習小項目我放在了github上,有興趣的同窗能夠fork下。

github: https://github.com/kaindy7633/todoList

相關文章
相關標籤/搜索