目录
1. 简介
2. 使用
1.简介
AngularJS是一个javascript框架
AngularJS 1.0 诞生于2009年,由Misko Hevery 等人创建,后为Google所收购。
通过指令(是以 ng 作为前缀)扩展了 HTML,通过表达式绑定数据到 HTML
2. 使用
引入(通常放在body内最后,提高加载速度)
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
例1:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl" ng-init="firstName='John'">
<p>姓名为 <span ng-bind="firstName"></span></p>
<p>名字 : <input type="text" ng-model="name"></p>
<h1>Hello {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John";
});
</script>
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</body>
</html>
说明:
ng-app指令 定义这是一个 AngularJS 代码段。
ng-controller指令 用于控制 AngularJS 代码段。
ng-model指令 把元素值(比如输入域的值)绑定到代码段。
ng-bind指令 把数据绑定到 HTML 视图
ng-init指令 初始化变量
表达式 {{ expression }},可以包含文字、运算符和变量
2.1 基础
表达式 {{ expression }}
与 ng-bind 指令 功能相同
<div ng-app="" ng-init="quantity=1;cost=5;firstName='John';lastName='Doe';person={firstName:'John',lastName:'Doe'};points=[1,15,19,2,40]">
<p>{{ 5 + 5 }}</p>
<p>{{ firstName + " " + lastName }}</p>
<p>{{ person.lastName }}</p>
<p>{{ points[2] }}</p>
<p> {{ quantity * cost }}</p>
等价
<p><span ng-bind="quantity * cost"></span></p>
</div>
JavaScript 表达式 与 AngularJS 表达式
相同点
1.可以包含字母,操作符,变量。
不同点
1.AngularJS 表达式可以写在 HTML 中。
2.AngularJS 表达式不支持条件判断,循环及异常。
3.AngularJS 表达式支持过滤器
指令
自定义指令
内置指令
自定义指令
<body ng-app="myApp">
<hello-word></hello-word>
<script>
var app = angular.module("myApp", []);
app.directive("helloWord", function() {
return {
/*
restrict : "A",
限制指令 只能通过特定的方式来调用(默认值为 EA)
E 作为元素名使用
A 作为属性使用
C 作为类名使用
M 作为注释使用
*/
template : "<h1>hello world!</h1>"
};
});
</script>
</body>
以下方式来调用指令(效果一样)
1.元素名
<hello-word></hello-word>
2.属性
<div hello-word></div>
3.类名
<div class="hello-word"></div>
4.注释
<!-- directive: hello-word -->
内置指令
ng-app指令 定义这是一个 AngularJS 代码段。
ng-controller指令 用于控制 AngularJS 代码段。
ng-model指令 把元素值(比如输入域的值)绑定到代码段。
ng-bind指令 把数据绑定到 HTML 视图,表达式原理也是通过该指令
ng-init指令 初始化变量,同行使用controller替代
ng-repeat指令 重复
ng-options指令 创建选择框
ng-disabled指令 是否可交互
ng-show指令 是否显示
ng-hide指令 是否隐藏
ng-click指令 事件
ng-include指令 包含HTML
ng-repeat指令(names数组可以是字符串、字典对象)
<div ng-app="myApp" ng-controller="customersCtrl">
列表
<li ng-repeat="x in names">
{{ x }}
</li>
表格
<table>
<tr ng-repeat="x in names | orderBy : 'Country'">
<td>{{ $index + 1 }}</td> 序号
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
<td ng-if="$odd" style="background-color:#f1f1f1">{{ x.Country }}</td>
<td ng-if="$even">{{ x.Country }}</td>
</tr>
</table>
</div>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
ng-model指令
1.为应用程序数据提供类型验证(number、email、required)。
2.为应用程序数据提供状态(invalid、dirty、touched、error)。
3.为 HTML 元素提供 CSS 类。
4.绑定 HTML 元素到 HTML 表单
验证用户输入
<form ng-app="" name="myForm">
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">不是一个合法的邮箱地址</span>
</form>
状态
ng-empty、ng-not-empty、ng-touched、ng-untouched、ng-valid、ng-invalid、ng-dirty、ng-pending、ng-pristine、
<form ng-app="" name="myForm" ng-init="myText = 'test@runoob.com'">
Email:
<input type="email" name="myAddress" ng-model="myText" required></p>
<h1>状态</h1>
{{myForm.myAddress.$valid}}
{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
</form>
基于状态CSS
<style>
input.ng-invalid {
background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
输入你的名字:
<input name="myAddress" ng-model="text" required>
</form>
绑定
<div ng-app="myApp" ng-controller="myCtrl">
名字: <input ng-model="name">
<h1>你输入了: {{name}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
// 初始值
$scope.name = "John Doe";
});
</script>
ng-options指令 创建选择框
<!--ng-options="x for (x, y) in sites" x键y值 字符串数组、对象数组-->
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-init="selectedName = names[0]" ng-model="selectedName" ng-options="x for x in names">
</select>
<!--也可使用ng-repeat创建选择框-->
<select>
<option ng-repeat="x in names">{{x}}</option>
</select>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Google", "Runoob", "Taobao"];
});
</script>
ng-disabled指令 是否可交互
// 和模型变量绑定
<button ng-disabled="mySwitch">点我!</button>
ng-show指令 是否显示
ng-hide指令 是否隐藏
<p ng-show="true">我是可见的。</p>
<p ng-hide="true">我是不可见的。</p>
<div ng-app="" ng-init="hour=13">
<p ng-show="hour > 12">我是可见的。</p>
</div>
ng-click指令 事件
<button ng-click="count = count + 1">点我!</button>
<button ng-click="toggle()">隐藏/显示</button>
$scope.toggle = function() {
};
模块 控制器 Scope
ng-app="myApp" 代表一个模块
ng-controller="myCtrl" 代表一个控制器
Scope 初始化model变量、函数
<div ng-app="myApp" ng-controller="myCtrl">
名: <input type="text" ng-model="firstName"><br>
<br>
名: {{firstName}}
<button ng-click='sayHello()'>点我</button>
</div>
<!--通常将script中的内容放在单独的js文件中,引用-->
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
// 有则初始化,没有则创建并初始化
// 变量、函数
$scope.firstName = "John";
$scope.sayHello = function() {
$scope.greeting = 'Hello ' + $scope.carname + '!';
};
// $rootScope,根作用域,可以作用所有ng-app的代码段
app.controller('myCtrl', function($scope, $rootScope) {
$rootScope.lastname = "Refsnes";
});
});
</script>
ng-include指令 包含其他HTML文件
<body ng-app="">
<div ng-include="'runoob.htm'"></div>
</body>
跨域包涵
<body ng-app="myApp">
<div ng-include="'http://c.runoob.com/runoobtest/angular_include.php'"></div>
<script>
var app = angular.module('myApp', [])
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'http://c.runoob.com/runoobtest/**'
]);
});
</script>
</body>
过滤器
使用一个管道字符 | 添加到表达式和指令中
指定过滤器:
currency 转化数字为货币格式。
filter 选择一个子集(从数组中)
lowercase 转小写
orderBy 排列数组(根据某个表达式)
uppercase 转大写
自定义过滤器
指定过滤器:
<p>姓名为 {{ lastName | uppercase }}</p>
<p>姓名为 {{ lastName | lowercase }}</p>
<p>总价 = {{ (quantity * price) | currency }}</p>
<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>
输入内容,过滤显示仅包含输入内容的项
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
自定义过滤器
<div ng-app="myApp" ng-controller="myCtrl">
姓名: {{ msg | reverse }}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.msg = "Runoob";
});
app.filter('reverse', function() { //可以注入依赖
return function(text) {
return text.split("").reverse().join("");
}
});
</script>
服务(Service)
服务是一个函数或对象
内置服务(30 多个)
自定义服务
例:
$location.absUrl() 当前页面的url
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $location) {
$scope.myUrl = $location.absUrl();
});
</script>
$http 服务(最常用)
向服务器发送请求获取并显示数据
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
// 简单的 GET 请求,可以改为 POST
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
// 简写
$http.get、$http.head、$http.post、$http.put、$http.delete、$http.jsonp、$http.patch
$http.get("http://www.runoob.com/try/angularjs/data/sites.php")
.then(function (response) {$scope.names = response.data.sites;});
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
});
$timeout 服务
定时器
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
$interval 服务
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
自定义服务
<script>
var app = angular.module('myApp', []);
app.service('helloWorld', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
// controller中使用服务
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = helloWorld.myFunc(255);
});
// 过滤器中使用服务
app.filter('myFormat',['hexafy', function(hexafy) {
return function(x) {
return hexafy.myFunc(x);
};
}]);
</script>
API
全局 API
angular.lowercase() 转小写
angular.uppercase() 转大写
angular.isString() 是否为字符串,是则true。
angular.isNumber() 是否为数字,是则true。
$scope.x2 = angular.lowercase("xxOO");
表单
<form ng-app="myApp" ng-controller="formCtrl"
novalidate>
输入框
First Name: <input type="text" ng-model="firstname">
多选框
<input type="checkbox" ng-model="myVar">
单选框
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="tuts">Tutorials
<input type="radio" ng-model="myVar" value="cars">Cars
下拉菜单
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="tuts">Tutorials
<option value="cars">Cars
</select>
按钮
<button ng-click="reset()">RESET</button>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
$scope.master = {firstName: "John", lastName: "Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
});
</script>
带验证的表单
$dirty 表单有填写记录
$valid 字段内容合法的
$invalid 字段内容是非法的
$pristine 表单没有填写记录
<form ng-app="myApp" ng-controller="validateCtrl"
name="myForm" novalidate>
<p>用户名:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">用户名是必须的。</span>
</span>
</p>
<p>邮箱:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">邮箱是必须的。</span>
<span ng-show="myForm.email.$error.email">非法的邮箱地址。</span>
</span>
</p>
<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = 'john.doe@gmail.com';
});
</script>
Bootstrap
<link rel="stylesheet" href="//apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.min.css">
可结合Bootstrap使用
动画
动画需适度
引入脚本
并<body ng-app="ngAnimate">
或var app = angular.module('myApp', ['ngAnimate']);
ngAnimate 会监测事件
ng-show、ng-hide、ng-class、ng-view、ng-include、ng-repeat、ng-if、ng-switch
<script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular-animate.min.js"></script>
<body ng-app="ngAnimate">
隐藏 DIV:
<input type="checkbox" ng-model="myCheck">
<div ng-hide="myCheck"></div>
</body>
css过渡
<style>
div {
transition: all linear 0.5s;
background-color: lightblue;
height: 100px;
}
.ng-hide {
height: 0;
}
</style>
css动画
<style>
@keyframes myChange {
from {
height: 100px;
} to {
height: 0;
}
}
div {
height: 100px;
background-color: lightblue;
}
div.ng-hide {
animation: 0.5s myChange;
}
</style>
依赖注入
value
factory
service
provider
constant
value 设置值
var mainApp = angular.module("mainApp", []);
mainApp.value("defaultInput", 5);
mainApp.controller('CalcController', function($scope, CalcService, defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);
$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
// 在 service 中注入 factory "MathService"
mainApp.service('CalcService', function(MathService){
this.square = function(a) {
return MathService.multiply(a,a);
}
});
provider
var mainApp = angular.module("mainApp", []);
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
constant
mainApp.constant("configParam", "constant value");
路由
通过不同的 URL( # + 标记 ) 访问不同的内容
ng-view用来显示不同内容
$routeProvider.when(url, {
向ng-view插入简单字符串,使用:
template: string,
向ng-view插入 HTML 模板文件,使用:
templateUrl: string,
function、string或数组类型,在当前模板上执行的controller函数,生成新的scope,使用:
controller: string, function 或 array,
string类型,为controller指定别名,使用:
controllerAs: string,
重定向的地址,使用:
redirectTo: string, function,
指定当前controller所依赖的其他模块,使用:
resolve: object<key, function>
});
例:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="http://apps.bdimg.com/libs/angular-route/1.3.13/angular-route.js"></script>
<script type="text/javascript">
angular.module('ngRouteExample', ['ngRoute'])
.controller('HomeController', function ($scope, $route) { $scope.$route = $route;})
.controller('AboutController', function ($scope, $route) { $scope.$route = $route;})
.config(function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'embedded.home.html',
controller: 'HomeController'
}).
when('/about', {
templateUrl: 'embedded.about.html',
controller: 'AboutController'
}).
otherwise({
redirectTo: '/home'
});
});
</script>
</head>
<body ng-app="ngRouteExample" class="ng-scope">
<script type="text/ng-template" id="embedded.home.html">
<h1> Home </h1>
</script>
<script type="text/ng-template" id="embedded.about.html">
<h1> About </h1>
</script>
<div>
<div id="navigation">
<a href="#/home">Home</a>
<a href="#/about">About</a>
</div>
<div ng-view="">
</div>
</div>
</body>
</html>
SPA
AngularJS 单页 Web 应用(single page web application,SPA)