第二章
- 实现计数器
<body ng-app> <!--ng-model将值绑定到HTML输入控件--> <input type="number" ng-model="value"/> <!--ng-click绑定事件--> <input type="button" ng-click="value=value+1" value="增加"/> </body>
- 模块和控制器和表达式
<body ng-app="app"> <div ng-controller="mainController"> <span>{{name}}</span> <button ng-click='say()'>登录</button> {{ fn() +5 }} {{ arr[2] }} </div> <script src="lib\angular.js"></script> <script> // 创建AngularJS的模块: // 第1个参数:AngularJS模块的模块名称 // 第1个参数:该模块所依赖的其他模块 var app = angular.module('app',[]); app.controller('mainController',function($scope){ $scope.name = "我是属性name的值"; $scope.say = function() { $scope.welcome= 'welcome:' + $scope.name + '!'; }; $scope.fn = function () { return 1; }; }); </script> </body>
- 模块间的相互依赖
<!--绑定demo模块--> <div ng-app="demo"> <!--绑定ctrls模块的MainController--> <div ng-controller="MainController"> <span>{{name}}</span> </div> </div> <script src="lib/angular.js"></script> <script> //创建ctrls模块 var ctrls = angular.module('ctrls',[]); // 在ctrls模块下创建了一个控制器 ctrls.controller('MainController', function ($scope) { $scope.name = "张三"; }); //创建demo模块,并依赖ctrls模块 var demo = angular.module('demo', ['ctrls']); </script>
- 根作用域【$rootScope】
<body> <div ng-app="demo"> <!--$rootScope有效,但是MainController的作用域无效--> <p>*ng-app="demo"作用域显示结果:</p> <span>{{rData}}</span> <span>{{data}}</span> <div ng-controller="MainController"> <!--$rootScope有效,但是MainController的作用域也有效--> <p>*ng-controller="MainController"作用域显示结果:</p> <span>{{rData}}</span> <span>{{data}}</span> </div> </div> <script src="lib/angular.js"></script> <script> var demo = angular.module('demo', []); //获取根作用域 demo.controller('MainController', function ($scope, $rootScope) { //使用根作用域定义属性rData $rootScope.rData = 'hello rootScope'; //使用MainController作用域定义属性data $scope.data = 'hello scope'; }) </script> </body>
- 作用域的嵌套
<body> <div ng-app="demo"> <div ng-controller="MainController"> <p>*ng-controller="MainController"作用域显示结果:</p> <!--MainController有效,但是DataController的作用域无效--> <span>{{mData}}</span> <span>{{dData}}</span> <div ng-controller="DataController"> <p>*ng-controller="DataController"作用域显示结果:</p> <!--MainController有效,DataController有效--> <span>{{mData}}</span> <span>{{dData}}</span> </div> </div> </div> <script src="lib/angular.js"></script> <script> var demo = angular.module('demo', []); //定义MainController控制器 demo.controller('MainController', function ($scope) { $scope.mData = "hello MainController"; }); //定义DataController控制器 demo.controller('DataController', function ($scope) { $scope.dData= "hello DataController"; }); </script> </body>
- 双向数据绑定
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>AngularJS双向绑定</title> </head> <body ng-app> 请输入内容:<input type="text" ng-model="demo"/><br/> 您输入的内容:{{demo}} <!--引入angular.js文件--> <script src="lib/angular.js"></script> </body> </html>
第三章
常用内置指令
- 框架
<!DOCTYPE html> <html lang="en"> <head></head> <body> <div ng-app="app"> <div ng-controller="MainController"> ... </div> </div> <script src="lib/angular.js"></script> <script> // 创建一个AngularJS模块。 var app = angular.module('app', []); app.controller('MainController', function ($scope) { $scope.XXX = 'XXX'; }); </script> </body> </html>
- 插值语法和ng-bind
<span>{{data}}</span> <span ng-bind="data"></span>
- 作用域样式属性
<div style="height: 100px;" ng-style="myStyle"></div>
- 绑定样式
// 在style标签里定义样式 .myColor .myDiv .myBorder <div style="height: 100px" ng-class="classOptions"></div> $scope.classOptions ={ myColor:true, myDiv:true, "myBorder":true // "myBorder":false }
- ng-show和ng-hide
<div style="width: 200px;height: 100px;background: red" ng-show="myTrue"> <div style="width: 200px;height: 100px;background:blue" ng-hide="myTrue"> $scope.myTrue=true; $scope.myFalse=false;
- ng-readonly【可用】和 on-disabled【禁用】
<input name="id1" type="text" ng-model="text" ng-readonly="boolean"> <input name="id2" type="text" ng-model="text" ng-disabled="boolean"> $scope.boolean = true;
- ng-click
<button ng-click="clickHandler()" onclick="onclickHandler()">按钮</button> $scope.clickHandler = function () { $scope.message = 'ng-click事件被触发。' } function onclickHandler() { console.log("onclick事件被触发"); }
- ng-change
<input type="text" ng-change="myFunc()" ng-model="myValue" /> $scope.myFunc = function() { $scope.message="输入框被修改了"; };
- ng-if
<!--使用ng-init始化属性myVar,值为false--> <input type="checkbox" ng-model="myVar" ng-init="myVar=false"> <div ng-if="myVar"> <h1>我来了</h1> </div>
- ng-switch
<div ng-switch="name"> <div ng-switch-when="张三"> this is 张三 </div> <div ng-switch-when="李四"> this is 李四 </div> <div ng-switch-default> 找不到此人 </div> </div> $scope.name = "李四"
- ng-repeat
<table style="border: solid 1px"> <!--ng-repeat会为每一item都绑定一个作用域。 这个作用域除了指定的每一项的数据对象外,还有$index、$first、$last……数据, 这些都是AngularJS自动生成的--> <tr ng-repeat="item in users"> <td>{{item.name}}</td> <td>{{item.sex}}</td> <td>{{item.age}}</td> <td>index:{{$index}}, first:{{$first}}, last:{{$last}}, middle:{{$middle}}, even:{{$even}}, odd:{{$odd}}</td> </tr> </table> $scope.users = [ {name: "张三", sex: "男", age: 24}, {name: "李四", sex: "女", age: 13}, {name: "王五", sex: "男", age: 38}, {name: "赵六", sex: "女", age: 55} ] // —————————————————————————————————————————————————————————————————————————————— <tr ng-repeat="item in numbers track by $index" > <td>{{item}}</td> <td>$index:{{$index}}</td> </tr> $scope.numbers = [1,1,4,2,5]; // —————————————————————————————————————————————————————————————————————————————— <tr ng-repeat="(key,value) in users"> <td>{{key}}</td> <td>{{value.sex}}</td> <td>{{value.age}}</td> </tr> $scope.users = { "张三": {age: 24, sex: "男"}, "李四": {age: 13, sex: "女"}, "王五": {age: 38, sex: "男"}, "赵六": {age: 55, sex: "女"} }
自定义指令
- 指令的作用域
- 基本框架
<!DOCTYPE html> <html lang="en"> <head></head> <body> <div ng-app="app"> <div><my-say-hello></my-say-hello></div> </div> <script src="lib/angular.js"></script> <script> var app = angular.module('app', []); /* 用directive创建指令, 第1个参数是指令的名字,指令的名字必须用驼峰法命名,是AngularJS的强制要求 第2个参数是指令的工厂函数,它的返回值是一个对象,该对象用于描述这个指令 */ app.directive('mySayHello', function () { // 返回的对象用于描述这个指令 return { // 定义指令的模板 template: "<p>hello world</p>", replace:false } }); </script> </body> </html>
- 指令的作用域
<div ng-app="app"> <div ng-init="myProperty='by-parent'"> {{ myProperty }} <div my-directive ng-init="myProperty='by my-child'"> {{ myProperty }} </div> </div> </div> <script src="lib/angular.js"></script> <script> var app = angular.module('app', []); app.directive('myDirective', function() { return { scope:true }; }) </script>
- 独立作用域
<body> <div ng-app="app"> <div ng-controller = 'insulate'> <user-info user-name="小明" age='num' speak='sayHello(name)'></user-info> </div> </div> <script src="lib/angular.js"></script> <script> var app = angular.module('app', []); // 定义父作用域 app.controller('insulate',function($scope){ // 定义父亲作用域的属性 $scope.num = 17; // 定义父作用域的函数 $scope.sayHello=function(name){ alert("Hello "+name); } }) // 添加自定义指令 app.directive('userInfo',function(){ return{ restrict:'EA', template:'姓名:<input type="text" ng-model="userName" /><br/>'+ '年龄: {{age}} <br/>'+ '<button class="btn btn-default" ng-click="speak({name:userName})">speaking</button><br/>' , scope:{ userName:'@', //绑定字面变量 age:'=', //绑定父作用域属性 speak:'&' //绑定父作用域函数 } } }); </script> </body>
第四章
- 作用域上的数据监听
<input type="text" ng-model="data"/> $scope.$watch('data', function (newValue, oldValue) { console.log('data has changed', ',', newValue, ',', oldValue); });
- $apply() 函数
<div ng-app="demo"> <div ng-controller="MainController"> <input type="number" ng-model="data"/> <button onclick="plusOne()">加1</button> </div> </div> <script src="lib/angular.js"></script> <script> var demo = angular.module('demo', []); demo.controller('MainController', function ($rootScope, $scope) { $scope.data = 1; window.scope = $scope; }); function plusOne() { window.scope.data += 1; window.scope.$apply();//删掉这一行,数据的改变将不会实时更新到视图 } </script>
- 依赖注入的三种方式
<body ng-app="myApp"> <div ng-controller="MyController"> <button ng-click="sayHello()">调用sayHello</button> </div> </body> <script src="lib/angular.js"></script> <script> // 1.行内注入 // var app=angular.module('myApp', []); // // 创建 value 对象 "temp" 并传递数据 // app.value("temp", "Hello"); // app.controller('MyController',['$scope','temp',function($scope,temp) {}; // $scope.sayHello = function() { // alert(temp); // } // }]); 2.显示注入 // var app=angular.module('myApp', []); // // 创建 value 对象 "temp" 并传递数据 // app.value("temp", "Hello"); // // var MyController = function($scope, temp) { // $scope.sayHello = function() { // alert(temp); // } // } // MyController.$inject = ['$scope','temp']; // app.controller('MyController', MyController); // 3.推断式注入 var app=angular.module('myApp', []); // 创建 value 对象 "temp" 并传递数据 app.value("temp", "Hello"); app.controller('MyController',function($scope,temp) { $scope.sayHello = function() { alert(temp); } }); </script>
第五章
创建服务
- 使用Provider创建服务
<script> var app = angular.module('app', []); //定义包含$get函数的函数myFunction var myFunction=function () { var name = 'world'; return { $get: function () { // 服务对象 return { msg: 'hello ' + name } }, changeName: function (newName) { name = newName; } } } // 使用provider()函数创建服务 app.provider('myService', myFunction); // 使用config()函数配置服务 app.config(function (myServiceProvider) { // 最后是 hello 张三 myServiceProvider.changeName('张三'); }); // 在控制器中注入服务myService app.controller('MainController', function ($scope, myService) { $scope.data = myService.msg; }); </script>
- 使用Factory创建服务
<script> var app = angular.module('app', []); // 定义函数,返回一个对象 var myFunction=function(){ return { msg: "this is data" } } // 在app模块下创建了一个服务,实例化服务对象 app.factory('myService', myFunction); // 在app模块下创建一个控制器,并在控制器的工厂函数中注入服务 app.controller('MainController', function ($scope, myService) { $scope.data = myService.msg; }); </script>
- 使用Service创建服务
<script> var app = angular.module('app',[]); //用service来创建服务,注入构造函数 app.service('myService',function(){ this.sayHello = function(name) { alert('hello ' + name) } }); //将服务myService注入到控制器 app.controller('MainController',function($scope,myService){ // 在控制器中定义函数,在函数内部调用服务的sayHello()函数 $scope.say=function(name){ myService.sayHello(name); } }); </script>
- 使用 constant 配置服务
<script> var app = angular.module('app',[]); app.provider('myService', function () { var name = 'world'; return { $get: function () { // 服务对象 return { msg: 'hello ' + name } }, changeName: function (newName) { name = newName; } } }); // 用constant来创建服务,注入函数 app.constant('country','China'); // app.value('country','China');使用这种方法会出现异常 // 使用config()函数配置服务 app.config(function(myServiceProvider,country){ myServiceProvider.changeName(country) }); // 在控制器中注入服务myService app.controller('MainController', function ($scope, myService) { $scope.data = myService.msg; }); </script>
服务类型
- $window
<script> var app = angular.module('myApp', []); app.controller('MainController', function($scope, $window) { //定义ng-click绑定的函数 $scope.displayAlert = function (msg) { $window.alert(msg); } }); </script>
- $location
<script> var app = angular.module('myApp', []); // 将 $location服务注入到控制器 app.controller('MainController', function($scope, $location) { $scope.host_Url = $location.host(); $scope.port_Url = $location.port(); $scope.protocol_Url = $location.protocol(); //传入myhash作为hash值 $scope.hash_Url = $location.hash('myhash').hash(); //传入/newPath作为子路径 $scope.path_Url = $location.path('/newPath').path(); //传入'name','lily'作为参数 $scope.search_Url = $location.search('name','lily').search(); $scope.url_Url = $location.url(); $scope.abs_Url = $location.absUrl(); }); </script>
-
w
a
t
c
h
监
听
watch监听
watch监听location
var app = angular.module('app', []); app.controller('MainController', function ($scope, $location) { $scope.locat = $location; // $watch监听的是AngularJS的表达式。 $scope.$watch('locat.path()', function (newValue, oldValue) { console.log(newValue); }); })
- $http服务
var app = angular.module('app', []); app.controller('MainController', function ($scope, $http) { $http({ method: 'GET', url: 'data.json' }).then(function successCallback(response) { $scope.msg = response.data.msg; }, function errorCallback(response) { console.log(response.data) console.log(response.status) }); });
路由
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS路由</title>
</head>
<body>
<div ng-app="app">
<a href="#!/index">index</a>
<a href="#!/first">demo5-7</a>
<a href="#!/about/2/lucy">lucy</a>
<a href="#!/about/3/banny">banny</a>
<div ng-view></div>
</div>
<script src="lib/angular.js"></script>
<script src="lib/angular-route.js"></script>
<script>
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/index', {
template: '<H2>{{name}}</H2>',
controller: function ($scope) {
$scope.name = 'index';
}
})
.when('/first', {
templateUrl:'demo5-7.html'//跳转至demo5-7.html
})
// 用:+字符串的方式,把网址里面的信息解析到$routeParams对象中去。
.when('/about/:id/:name', {
template: '<H2>{{params}}</H2>',
controller: function ($scope, $routeParams) {
$scope.params=$routeParams
}
})
.otherwise({
redirectTo: '/index'
});
});
</script>
</body>
</html>