AngularJS 教程
AngularJS 教程
AngularJS 是 Google 推出的早期前端 MVVM 框架,通过双向数据绑定与指令系统,让开发者用最少的代码构建动态 Web 应用。虽然新项目已推荐使用 Angular 2+ 或 Vue/React,但 AngularJS(1.x)仍在大量存量系统中运行。
核心特性
- 双向数据绑定:模型变化自动更新视图,视图操作自动同步模型
- 指令系统:通过
ng-*指令扩展 HTML - 依赖注入:模块化开发,便于测试与维护
- MVC 架构:模型(Model)、视图(View)、控制器(Controller)分离
引入方式
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
第一个应用
<html ng-app>
<body>
<div>
<label>姓名:</label>
<input type="text" ng-model="name">
<h1>你好, {{name}}!</h1>
</div>
<script src="angular.min.js"></script>
</body>
</html>
输入框内容会实时反映到标题中,这就是双向绑定的魅力。
学习路线
- 表达式与指令
- 控制器、过滤器、Service
- Http 请求、Select 下拉、表格
- SQL、HTML DOM、事件、模块
- 综合应用与参考手册
AngularJS 简介
AngularJS 简介
1. 什么是 AngularJS
AngularJS 诞生于 2009 年,由 Google 维护,是 MVC 架构的现代前端框架,用 JavaScript 编写,可添加到任何 HTML 页面。
2. 核心概念
- ng-app:定义 AngularJS 应用根元素
- ng-model:绑定输入控件到数据模型
- ng-bind:单向绑定数据到 HTML
- {{ }}:插值表达式,输出模型值
- controller:控制器,管理数据与逻辑
3. 双向数据绑定
<div ng-app="">
<p>输入内容:<input type="text" ng-model="text"></p>
<p>实时显示:{{text}}</p>
</div>
4. 为什么用 AngularJS
- 双向绑定减少 DOM 操作代码
- 内置验证、过滤器等实用功能
- 指令系统扩展 HTML 能力
- 依赖注入让代码可测试
5. 与 Angular 2+ 的区别
| 特性 | AngularJS(1.x) | Angular(2+) |
|---|---|---|
| 语言 | JavaScript | TypeScript |
| 架构 | MVC + 作用域 | 组件化 + 模块化 |
| 数据绑定 | 双向绑定默认 | 单向为主,显式双向 |
| 状态 | 已停止新特性开发 | 活跃维护 |
AngularJS 表达式
AngularJS 表达式
AngularJS 表达式写在双大括号 {{ }} 中,在 HTML 中输出数据。与 JavaScript 表达式类似,但更安全、更简单。
1. 基本表达式
<div ng-app="" ng-init="a=5; b=3">
<p>加法: {{ a + b }}</p> <!-- 8 -->
<p>乘法: {{ a * b }}</p> <!-- 15 -->
<p>字符串: {{ "Hello" + " World" }}</p>
<p>对象: {{ {name: "张三"}.name }}</p>
<p>数组: {{ [1,2,3][1] }}</p> <!-- 2 -->
</div>
2. 与 ng-bind 等价
<div ng-app="" ng-init="name='AngularJS'">
<p>插值方式: {{ name }}</p>
<p ng-bind="name">ng-bind 方式</p>
</div>
3. 表达式特点
- 支持数字、字符串、对象、数组
- 支持算术、比较、逻辑运算符
- 不支持条件语句、循环、异常(非流程控制)
- 不区分 undefined 与 null,出错时输出空
4. 常用运算示例
<div ng-app="" ng-init="price=100; qty=3; rate=0.1">
<p>单价: {{ price }}</p>
<p>数量: {{ qty }}</p>
<p>小计: {{ price * qty }}</p>
<p>折扣后: {{ price * qty * (1 - rate) }}</p>
<p>比较: {{ price > 50 ? "贵" : "便宜" }}</p>
</div>
AngularJS 指令
AngularJS 指令
指令是带有 ng- 前缀的 HTML 属性,用于扩展 HTML 功能、操作 DOM 与数据。
1. 核心指令
<div ng-app="" ng-init="visible=true; items=['苹果','香蕉','橙子']">
<!-- ng-init:初始化变量 -->
<p ng-init="x=10">x = {{x}}</p>
<!-- ng-if:条件渲染 -->
<p ng-if="visible">这是可见的内容</p>
<!-- ng-show / ng-hide:显示隐藏 -->
<p ng-show="visible">show 控制</p>
<p ng-hide="visible">hide 控制</p>
<!-- ng-repeat:循环 -->
<ul>
<li ng-repeat="item in items">{{ item }}</li>
</ul>
</div>
2. 常用指令一览
| 指令 | 作用 |
|---|---|
| ng-app | 定义应用根元素 |
| ng-model | 双向绑定输入控件 |
| ng-bind | 绑定数据到元素文本 |
| ng-repeat | 遍历数组/对象生成元素 |
| ng-if | 条件渲染(移除/重建 DOM) |
| ng-show/ng-hide | CSS 方式显示/隐藏 |
| ng-class | 动态绑定 CSS 类 |
| ng-click | 点击事件 |
| ng-disabled | 禁用控件 |
| ng-options | 下拉选项绑定 |
3. 动态类与事件
<div ng-app="" ng-init="isActive=true">
<button
ng-class="{active: isActive}"
ng-click="isActive = !isActive">
点击切换: {{ isActive }}
</button>
</div>
AngularJS 控制器
AngularJS 控制器
控制器(Controller)通过 ng-controller 指令绑定到 HTML,负责管理视图的数据与行为。
1. 基本控制器
<div ng-app="myApp" ng-controller="userCtrl">
<p>姓名: {{ user.name }}</p>
<p>年龄: {{ user.age }}</p>
<button ng-click="grow()">长大一岁</button>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("userCtrl", function($scope) {
$scope.user = {
name: "张三",
age: 25
};
$scope.grow = function() {
$scope.user.age++;
};
});
</script>
2. $scope 作用域
$scope 是控制器与视图之间的桥梁,暴露数据和方法给模板:
app.controller("msgCtrl", function($scope) {
$scope.message = "Hello World";
$scope.reverse = function() {
$scope.message = $scope.message.split("").reverse().join("");
};
});
3. 控制器中的属性
<div ng-app="myApp" ng-controller="calcCtrl">
<input type="number" ng-model="num1">
<input type="number" ng-model="num2">
<p>和: {{ num1 + num2 }}</p>
<p>积: {{ multiply() }}</p>
</div>
<script>
app.controller("calcCtrl", function($scope) {
$scope.num1 = 0;
$scope.num2 = 0;
$scope.multiply = function() {
return $scope.num1 * $scope.num2;
};
});
</script>
4. 控制器嵌套(父子作用域)
<div ng-controller="parentCtrl">
<p>父级: {{ parentData }}</p>
<div ng-controller="childCtrl">
<p>子级可访问: {{ parentData }}</p>
<p>子级: {{ childData }}</p>
</div>
</div>
AngularJS 过滤器
AngularJS 过滤器
过滤器通过管道符 | 使用,用于格式化或筛选数据显示。
1. 内置过滤器
<div ng-app="" ng-init="
price=1234.5678;
name='angularjs';
date=new Date();
items=['香蕉','苹果','橙子']
">
<!-- currency:货币 -->
<p>{{ price | currency }}</p> <!-- $1,234.57 -->
<p>{{ price | currency:"¥" }}</p> <!-- ¥1,234.57 -->
<!-- number:数字格式 -->
<p>{{ price | number:2 }}</p> <!-- 1,234.57 -->
<!-- uppercase / lowercase -->
<p>{{ name | uppercase }}</p> <!-- ANGULARJS -->
<p>{{ "HELLO" | lowercase }}</p>
<!-- date:日期格式 -->
<p>{{ date | date:"yyyy-MM-dd HH:mm" }}</p>
<!-- orderBy:排序 -->
<p>{{ items | orderBy }}</p>
<!-- limitTo:限制长度 -->
<p>{{ items | limitTo:2 }}</p>
<!-- json:格式化输出 -->
<pre>{{ {a:1, b:2} | json }}</pre>
</div>
2. filter:筛选
<div ng-app="" ng-controller="listCtrl">
<input type="text" ng-model="search">
<ul>
<li ng-repeat="p in people | filter:search">
{{ p.name }} - {{ p.city }}
</li>
</ul>
</div>
3. 自定义过滤器
app.filter("reverse", function() {
return function(input) {
return input.split("").reverse().join("");
};
});
// 使用
// {{ "hello" | reverse }} → olleh
4. 过滤器链式调用
<p>{{ "angularjs" | uppercase | limitTo:5 }}</p>
<!-- ANGUL -->
AngularJS Service
AngularJS Service
Service 是 AngularJS 中共享数据与逻辑的机制,通过依赖注入使用,避免代码重复。
1. 内置 Service
app.controller("demoCtrl", function($scope, $http, $location, $timeout) {
// $http:发起 AJAX 请求
// $location:获取/修改 URL
// $timeout:延时执行
// $window:窗口对象
// $filter:在 JS 中使用过滤器
});
2. $http 示例
app.controller("apiCtrl", function($scope, $http) {
$http.get("https://api.example.com/users")
.then(function(response) {
$scope.users = response.data;
}, function(error) {
$scope.error = "请求失败: " + error.status;
});
});
3. 自定义 Service
// 方式一:factory(返回对象)
app.factory("userService", function() {
var users = ["张三", "李四"];
return {
list: function() { return users; },
add: function(name) { users.push(name); }
};
});
// 方式二:service(构造函数)
app.service("mathService", function() {
this.add = function(a, b) { return a + b; };
});
// 方式三:value/constant(常量)
app.value("apiBase", "https://api.example.com");
app.constant("APP_NAME", "我的应用");
4. 注入使用
app.controller("userCtrl", function($scope, userService, mathService, apiBase) {
$scope.users = userService.list();
$scope.sum = mathService.add(3, 4);
$scope.base = apiBase;
});
5. $location 示例
app.controller("navCtrl", function($scope, $location) {
$scope.currentPath = $location.path();
$scope.goHome = function() {
$location.path("/home");
};
});
AngularJS Http
AngularJS Http
$http 服务封装了 AJAX 请求,支持 Promise,是 AngularJS 与后端通信的标准方式。
1. GET 请求
app.controller("getCtrl", function($scope, $http) {
$http.get("https://api.example.com/posts")
.then(function(response) {
// 成功回调
$scope.posts = response.data;
console.log("状态码:", response.status);
})
.catch(function(error) {
$scope.error = "请求出错: " + error.statusText;
});
});
2. POST 请求
app.controller("postCtrl", function($scope, $http) {
$scope.submit = function() {
var data = { title: $scope.title, body: $scope.body };
$http({
method: "POST",
url: "https://api.example.com/posts",
data: data,
headers: { "Content-Type": "application/json" }
}).then(function(response) {
$scope.result = response.data;
});
};
});
3. 简写方法
$http.get(url) $http.post(url, data) $http.put(url, data) $http.delete(url) $http.head(url) $http.jsonp(url) // JSONP 跨域
4. 完整配置对象
$http({
method: "GET",
url: "/api/users",
params: { page: 1, size: 20 }, // URL 查询参数
data: {}, // 请求体
timeout: 5000, // 超时(毫秒)
headers: {
"Authorization": "Bearer token123",
"Accept": "application/json"
},
responseType: "json"
}).then(function(res) {
$scope.data = res.data;
}, function(err) {
console.error("错误:", err);
});
5. 加载状态处理
app.controller("loadCtrl", function($scope, $http) {
$scope.loading = false;
$scope.load = function() {
$scope.loading = true;
$http.get("/api/data")
.then(function(r) {
$scope.data = r.data;
})
.finally(function() {
$scope.loading = false;
});
};
});
AngularJS Select
AngularJS Select
AngularJS 通过 ng-options 或 ng-repeat 动态生成下拉选择框。
1. ng-options 基本用法
<div ng-app="myApp" ng-controller="selectCtrl">
<select ng-model="selected" ng-options="city for city in cities">
<option value="">-- 请选择城市 --</option>
</select>
<p>你选择了: {{ selected }}</p>
</div>
<script>
app.controller("selectCtrl", function($scope) {
$scope.cities = ["北京", "上海", "广州", "深圳"];
});
</script>
2. 对象数组选项
<select ng-model="selUser"
ng-options="u.name for u in users">
<option value="">请选择用户</option>
</select>
<p>选中对象: {{ selUser.name }} / {{ selUser.age }} 岁</p>
<script>
$scope.users = [
{ id: 1, name: "张三", age: 25 },
{ id: 2, name: "李四", age: 30 },
{ id: 3, name: "王五", age: 28 }
];
</script>
3. 键值形式(分组)
<!-- 键值对形式 -->
<select ng-model="sel"
ng-options="key as value for (key, value) in map">
</select>
<!-- 分组显示 -->
<select ng-model="selFruit"
ng-options="f.name group by f.type for f in fruits">
</select>
4. 使用 ng-repeat 替代
<select ng-model="selected">
<option ng-repeat="c in cities" value="{{c}}">{{c}}</option>
</select>
<!-- 注意:ng-repeat 的 value 是字符串,与 ng-options 不同 -->
5. 联动下拉
<select ng-model="province" ng-change="loadCity()">
<option ng-repeat="p in provinces" value="{{p}}">{{p}}</option>
</select>
<select ng-model="city" ng-disabled="!province">
<option ng-repeat="c in cities[province] || []">{{c}}</option>
</select>
AngularJS 表格
AngularJS 表格
结合 ng-repeat 与过滤器,AngularJS 可以轻松渲染、排序、筛选表格数据。
1. 基本表格
<div ng-app="myApp" ng-controller="tableCtrl">
<table border="1">
<tr>
<th>编号</th><th>姓名</th><th>城市</th><th>工资</th>
</tr>
<tr ng-repeat="e in employees">
<td>{{ e.id }}</td>
<td>{{ e.name }}</td>
<td>{{ e.city }}</td>
<td>{{ e.salary | currency:"¥" }}</td>
</tr>
</table>
</div>
<script>
app.controller("tableCtrl", function($scope) {
$scope.employees = [
{ id: 1, name: "张三", city: "北京", salary: 12000 },
{ id: 2, name: "李四", city: "上海", salary: 15000 },
{ id: 3, name: "王五", city: "广州", salary: 9800 }
];
});
</script>
2. 排序显示(序号)
<!-- $index 是循环索引 -->
<tr ng-repeat="e in employees">
<td>{{ $index + 1 }}</td>
<td>{{ e.name }}</td>
</tr>
3. 过滤搜索表格
<input type="text" ng-model="searchText">
<table>
<tr ng-repeat="e in employees | filter:searchText">
<td>{{ e.name }}</td>
<td>{{ e.city }}</td>
</tr>
</table>
<!-- 按字段精确筛选 -->
<tr ng-repeat="e in employees | filter:{city: selectedCity}">
</tr>
4. 排序表格
<!-- 点击表头排序: -->
<th ng-click="sortField='name'">姓名</th>
<th ng-click="sortField='salary'">工资</th>
<tr ng-repeat="e in employees | orderBy:sortField">
<td>{{ e.name }}</td>
<td>{{ e.salary }}</td>
</tr>
<!-- 倒序:orderBy:'-salary' -->
<tr ng-repeat="e in employees | orderBy:'-salary'"></tr>
5. 空状态提示
<tr ng-if="(employees | filter:searchText).length === 0"> <td colspan="3">没有匹配的数据</td> </tr>
AngularJS SQL
AngularJS SQL
AngularJS 前端本身不直接操作数据库,通常通过后端 API(如 PHP/Node/Java)执行 SQL 并返回 JSON。
1. 后端提供 JSON 接口
// PHP 示例:get_users.php
<?php
$conn = new mysqli("localhost", "user", "pass", "db");
$result = $conn->query("SELECT * FROM users");
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
header("Content-Type: application/json");
echo json_encode($rows);
?>
2. 前端获取并展示
app.controller("sqlCtrl", function($scope, $http) {
$http.get("get_users.php")
.then(function(response) {
$scope.users = response.data;
});
});
<table>
<tr ng-repeat="u in users">
<td>{{ u.id }}</td>
<td>{{ u.name }}</td>
<td>{{ u.email }}</td>
</tr>
</table>
3. 带参数查询
// 后端:search_users.php?keyword=张
$keyword = $_GET["keyword"];
$stmt = $conn->prepare("SELECT * FROM users WHERE name LIKE ?");
$like = "%" . $keyword . "%";
$stmt->bind_param("s", $like);
$stmt->execute();
$result = $stmt->get_result();
// 前端传参
$scope.search = function() {
$http.get("search_users.php", {
params: { keyword: $scope.keyword }
}).then(function(r) { $scope.users = r.data; });
};
4. 增删改请求
$http.post("add_user.php", {
name: $scope.newName,
email: $scope.newEmail
});
$http.delete("delete_user.php?id=" + id);
$http.post("update_user.php", {
id: id, name: $scope.editName
});
5. 安全建议
- 后端使用参数化查询(PDO 预处理),防止 SQL 注入
- 验证输入数据,过滤特殊字符
- 接口做权限校验
- 返回 JSON 统一格式:
{code, msg, data}
AngularJS HTML DOM
AngularJS HTML DOM
AngularJS 提供 ng-disabled、ng-show、ng-click 等指令直接控制 HTML DOM 状态,无需手动 jQuery 操作。
1. ng-disabled 禁用
<div ng-app="" ng-init="isDisabled=false">
<button ng-disabled="isDisabled">按钮</button>
<p>
<input type="checkbox" ng-model="isDisabled"> 禁用按钮
</p>
</div>
2. ng-show / ng-hide
<div ng-app="" ng-init="show=true"> <button ng-click="show = !show">切换</button> <!-- ng-show:display:none 隐藏 --> <p ng-show="show">显示的段落(display) </p> <!-- ng-hide:相反 --> <p ng-hide="show">隐藏的段落</p> <!-- ng-if:从 DOM 移除 --> <p ng-if="show">ng-if 条件内容</p> </div>
3. ng-click 事件
<div ng-app="" ng-controller="domCtrl">
<p>点击次数: {{ count }}</p>
<button ng-click="count = count + 1">加一</button>
<button ng-click="count = 0">重置</button>
</div>
<script>
app.controller("domCtrl", function($scope) {
$scope.count = 0;
});
</script>
4. ng-class 动态样式
<style>
.active { color: green; font-weight: bold; }
.error { color: red; }
</style>
<div ng-app="" ng-init="status='active'">
<p ng-class="{active: status==='active', error: status==='error'}">
状态文本
</p>
<select ng-model="status">
<option value="active">正常</option>
<option value="error">错误</option>
</select>
</div>
5. 其他 DOM 指令
ng-show / ng-hide 显示隐藏 ng-if 条件渲染 ng-disabled 禁用 ng-readonly 只读 ng-checked 勾选状态 ng-selected 选中状态 ng-style 动态内联样式 ng-class 动态类 ng-change 值变化事件 ng-dblclick 双击事件 ng-mouseenter 鼠标进入
AngularJS 事件
AngularJS 事件
AngularJS 用 ng-* 指令绑定 DOM 事件,事件处理器写在控制器中,通过 $scope 暴露。
1. 常用事件指令
<div ng-app="myApp" ng-controller="eventCtrl">
<button ng-click="say('单击')">单击</button>
<button ng-dblclick="say('双击')">双击</button>
<button ng-mousedown="say('按下')">按下</button>
<button ng-mouseup="say('松开')">松开</button>
<button ng-mouseenter="say('进入')">进入</button>
<button ng-mouseleave="say('离开')">离开</button>
<input ng-focus="say('聚焦')" ng-blur="say('失焦')"
ng-keyup="say('按键:' + $event.key)">
<p>{{ message }}</p>
</div>
<script>
app.controller("eventCtrl", function($scope) {
$scope.say = function(msg) {
$scope.message = msg;
};
});
</script>
2. $event 对象
<button ng-click="getInfo($event)">查看事件</button>
$scope.getInfo = function(e) {
console.log("目标:", e.target);
console.log("坐标:", e.clientX, e.clientY);
console.log("按键:", e.which);
e.preventDefault(); // 阻止默认行为
};
3. 键盘事件
<input type="text" ng-keypress="onKey($event)">
$scope.onKey = function(e) {
if (e.keyCode === 13) { // 回车
$scope.submit();
}
if (e.keyCode === 27) { // Esc
$scope.cancel();
}
};
4. 表单事件
<form>
<input ng-model="email" ng-change="onChange()">
<select ng-model="city" ng-change="loadArea()">...</select>
</form>
$scope.onChange = function() {
// 值变化时触发
$scope.valid = $scope.email.indexOf("@") > -1;
};
AngularJS 模块
AngularJS 模块
模块(Module)是 AngularJS 应用的组织单元,定义了控制器、服务、过滤器、指令的作用域。
1. 定义模块
// 创建模块(第二个参数[]表示依赖列表)
var app = angular.module("myApp", []);
// 获取已有模块(不传第二个参数)
var app2 = angular.module("myApp");
2. 模块挂载
<html ng-app="myApp">
也可以指定区域:
<div ng-app="myApp"> <div ng-controller="ctrl1">...</div> <div ng-controller="ctrl2">...</div> </div>
3. 模块添加内容
app.controller("c1", function($scope) { ... });
app.factory("svc", function() { ... });
app.directive("myDirective", function() { ... });
app.filter("myFilter", function() { ... });
app.config(function() { ... }); // 配置阶段
app.run(function() { ... }); // 运行阶段
4. 模块依赖
// 引入第三方模块 ngRoute(路由)
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/home", { templateUrl: "home.html" })
.when("/about", { templateUrl: "about.html" })
.otherwise({ redirectTo: "/home" });
});
5. 多模块协作
// 模块 A:核心模块
angular.module("core", []);
// 模块 B:用户模块,依赖 core
angular.module("user", ["core"]);
// 主模块组合
var app = angular.module("myApp", ["core", "user"]);
6. 为什么用模块
- 避免全局变量污染
- 依赖清晰,便于测试
- 代码按业务拆分,便于维护
- 加载顺序管理
AngularJS 应用
AngularJS 应用
综合前面的知识,构建一个完整的 AngularJS 单页应用。
1. 应用结构
index.html <!-- 入口 --> js/ app.js <!-- 模块定义 --> controllers.js <!-- 控制器 --> services.js <!-- 服务 --> views/ home.html list.html detail.html
2. app.js
var app = angular.module("todoApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", { templateUrl: "views/home.html", controller: "homeCtrl" })
.when("/list", { templateUrl: "views/list.html", controller: "listCtrl" })
.otherwise({ redirectTo: "/" });
});
3. controllers.js(待办清单)
app.controller("homeCtrl", function($scope) {
$scope.title = "待办清单";
});
app.controller("listCtrl", function($scope) {
$scope.todos = [
{ text: "学习 AngularJS", done: false },
{ text: "写示例代码", done: true },
{ text: "部署上线", done: false }
];
$scope.add = function() {
if ($scope.newTodo) {
$scope.todos.push({ text: $scope.newTodo, done: false });
$scope.newTodo = "";
}
};
$scope.remove = function(todo) {
var idx = $scope.todos.indexOf(todo);
$scope.todos.splice(idx, 1);
};
});
4. views/list.html
<h2>我的待办</h2>
<input ng-model="newTodo" ng-keyup="$event.keyCode===13 && add()"
placeholder="输入任务按回车">
<ul>
<li ng-repeat="t in todos">
<input type="checkbox" ng-model="t.done">
<span ng-class="{done: t.done}">{{ t.text }}</span>
<button ng-click="remove(t)">删除</button>
</li>
</ul>
5. 应用启动
<html ng-app="todoApp">
<body>
<nav>
<a href="#/">首页</a>
<a href="#/list">清单</a>
</nav>
<div ng-view></div> <!-- 路由视图容器 -->
</body>
</html>
AngularJS 实例
AngularJS 实例
通过几个常见实例巩固 AngularJS 的核心用法。
1. 计算器
<div ng-app="calcApp" ng-controller="calcCtrl">
<input type="number" ng-model="a">
<select ng-model="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" ng-model="b">
<p>结果: {{ calc() }}</p>
</div>
<script>
angular.module("calcApp", [])
.controller("calcCtrl", function($scope) {
$scope.a = 0; $scope.b = 0; $scope.op = "+";
$scope.calc = function() {
switch ($scope.op) {
case "+": return $scope.a + $scope.b;
case "-": return $scope.a - $scope.b;
case "*": return $scope.a * $scope.b;
case "/": return $scope.b !== 0 ? $scope.a / $scope.b : "不能除0";
}
};
});
</script>
2. 表单验证
<form name="myForm" ng-app="formApp" ng-controller="formCtrl"
ng-submit="submit()" novalidate>
<input name="email" type="email" ng-model="user.email" required>
<p ng-show="myForm.email.$error.email">邮箱格式错误</p>
<p ng-show="myForm.email.$error.required">邮箱必填</p>
<input name="pwd" type="password" ng-model="user.pwd"
ng-minlength="6" required>
<p ng-show="myForm.pwd.$error.minlength">密码至少6位</p>
<button ng-disabled="myForm.$invalid">提交</button>
</form>
3. 购物车小计
<tr ng-repeat="item in cart">
<td>{{ item.name }}</td>
<td><input type="number" ng-model="item.qty"></td>
<td>{{ item.price | currency:"¥" }}</td>
<td>{{ item.price * item.qty | currency:"¥" }}</td>
</tr>
<tr>
<td colspan="3">合计</td>
<td>{{ total() | currency:"¥" }}</td>
</tr>
$scope.total = function() {
var sum = 0;
angular.forEach($scope.cart, function(item) {
sum += item.price * item.qty;
});
return sum;
};
4. 时钟
app.controller("clockCtrl", function($scope, $interval) {
$scope.time = new Date();
$interval(function() {
$scope.time = new Date();
}, 1000);
});
AngularJS 参考手册
AngularJS 参考手册
1. 常用指令速查
| 指令 | 说明 |
|---|---|
| ng-app | 定义应用根元素 |
| ng-controller | 绑定控制器 |
| ng-model | 双向数据绑定 |
| ng-bind | 单向输出数据 |
| ng-repeat | 循环渲染 |
| ng-if | 条件渲染 |
| ng-show / ng-hide | 显示 / 隐藏 |
| ng-class | 动态 CSS 类 |
| ng-style | 动态内联样式 |
| ng-click / ng-dblclick | 单击 / 双击 |
| ng-change | 值变化事件 |
| ng-disabled / ng-readonly | 禁用 / 只读 |
| ng-options | 下拉选项 |
| ng-submit | 表单提交 |
| ng-init | 初始化变量 |
| ng-view | 路由视图容器 |
2. 过滤器速查
currency 货币格式化 number 数字格式(小数位) date 日期格式化 uppercase 转大写 lowercase 转小写 limitTo 限制长度 orderBy 排序 filter 筛选 json JSON 格式化
3. 内置服务速查
$http AJAX 请求 $location URL 操作 $route (ngRoute) 路由 $timeout 延时执行 $interval 周期执行 $window 窗口对象 $document 文档对象 $filter 调用过滤器 $scope 作用域 $rootScope 根作用域
4. $scope 常用方法
$watch(expr, fn) 监听数据变化 $apply(fn) 手动触发脏检查 $on(event, fn) 监听事件 $emit(name) 向上广播事件 $broadcast(name) 向下广播事件
5. 全局 API
angular.module("m", []) 定义模块
angular.element(el) 包装 jQuery 对象
angular.isArray / isObject 类型判断
angular.forEach(arr, fn) 遍历
angular.extend(obj, src) 对象扩展
angular.copy(obj) 深拷贝
angular.toJson / fromJson JSON 转换
6. 版本说明
AngularJS 1.x 已进入维护末期,官方建议新项目使用 Angular(2+)、React 或 Vue。学习 AngularJS 有助于理解存量系统与 MVVM 思想。