基本示例
index.html
<!-- 本段示例代码来自 AngularJS 官方站点 angularjs.org -->
<!doctype html>
<!-- ng-app 表示在当前区域内启用 AngularJS -->
<html ng-app>
<head>
<!-- 载入 AngularJS 文件 -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<!-- ng-model 表示当前控件与指定 model 关联。控件变更时,model 也会改变,反之亦然 -->
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<!-- {{ }} 用于绑定 model。当 model 的值改变,此处的显示也会改变 -->
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
使用控件
index.html
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<!-- 业务逻辑依然通过 JavaScript 实现 -->
<script src="todo.js"></script>
<link rel="stylesheet" href="todo.css">
</head>
<body>
<h2>Todo</h2>
<!-- 该 div 的行为将通过 TodoListController 类控制 -->
<div ng-controller="TodoListController as todoList">
<span>{{todoList.remaining()}} of {{todoList.todos.length}} remaining</span>
<!-- ng-click 定义了点击时将调用哪个方法 -->
[ <a href="" ng-click="todoList.archive()">archive</a> ]
<ul class="unstyled">
<!-- ng-repeat 可自动遍历并向 DOM 添加元素 -->
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
<!-- 点击按钮时将调用 addTodo() -->
<form ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</body>
</html>
todo.js
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
// 默认添加两条条目
todoList.todos = [
{text:'learn angular', done:true},
{text:'build an angular app', done:false}];
todoList.addTodo = function() {
// 借助 Array.push() 插入条目
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
todoList.remaining = function() {
var count = 0;
angular.forEach(todoList.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
todoList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
});
todo.css
.done-true {
text-decoration: line-through;
color: grey;
}
未完待续