angularjs简介
手册:http://docs.angularjs.cn/api
官网 : 官网
适合场景: CRUD(ajax前后端交互) 应用 , SPA 单页面的网站开发
不适合: 游戏,图形,界面,可视化
CRUD: 增加(Create)、读取(Retrieve)(重新得到数据)、更新(Update)和删除(Delete)几个单词的首字母简写。主要被用在描述软件系统中数据库或者持久层的基本操作功能. —- [百度百科]
SPA : 单页面 —- [segmentfault]
另外(国内几个社区): http://www.angularjs.cn http://www.ngnice.com http://woxx.sinaapp.com
angularJs有哪些特性?
- MVC模式
- 模块系统
- 指令系统
- 依赖注入
- 双向数据绑定
angularJs的MVC方式
- 数据的挂载
- ng-controller
- 双大括号表达式
angularJs的作用域
- $scope
- $rootScope
- 依赖注入
- 服务
ng简单使用
简单使用1 — [mvc模式, scope, rootScope,双大括号表达式]
<!DOCTYPE HTML>
<html ng-app>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script src="angular.min.js"></script>
<script>
function Aaa($scope,$rootScope){
$scope.name = 'hello';
$rootScope.root = "我是root";
}
function Bbb($scope){
$scope.name = 'hi';
}
</script>
</head>
<body>
<div ng-controller="Aaa">
<p>{{name}}</p>
<div ng-controller="Bbb">
<p>{{name}}</p>
<p>{{age}}</p>
</div>
</div>
<div ng-controller="Bbb">
<p>{{root}}</p>
</div>
</body>
</html>
注意点:
- html标签上的ng-* * * (目前是controller)。?
- 回调controller中的函数。?
- 回调参数: scope rootScope 区别?
- html标签上面的ng-app ? ↓
简单使用2 — 指令系统 ;
ng-开头的叫做指令
ng-app 初始化,可以写在任何标签上面。
ng-controller 数据和视图的桥梁。
简单使用3 — 双向数据绑定 ;
- MVVM —
数据
和视图
同时改变(若数据改变,视图跟着改
|若视图改变,数据跟着改
) - $timeout
- ng-click
- ng-model
利用setTimeout来改变内容
function Aaa($scope,$timeout){
$scope.name = 'hello';
/*setTimeout(function(){
$scope.name = 'hi';
},2000);*/
$timeout(function(){
$scope.name = 'hi, setTimeout';
},2000);
$scope.show = function(){
$scope.name = 'hi';
};
}
<div ng-controller="Aaa" ng-click="show()" ng-app>
<input type="text" ng-model="name"/>
<p>{{name}}</p>
</div>
注意点:
1. setTimeout不可用 –> $.setTimeout
2. 用ng-click/mousexxxxx可以绑定事件
3. ng-model 双绑的栗子
mvvm ->>
简单使用4 — 过滤器 – 购物车突入 ;
- 过滤器
- currency
- 过滤器过滤,
- 数量*个数,
- 监听angularjs的变化
function Aaa($scope,$timeout){
$scope.iphone = {
money : 5,
num : 1,
fre : 10
};
$scope.sum = function(){
return $scope.iphone.money * $scope.iphone.num; // 不要忘记加上 $scope 前缀
};
/*$scope.$watch('iphone.money',function(newVal,oldVal){
console.log(newVal);
console.log(oldVal);
},true);*/
/*
$scope.$watch (
所要监听的函数或者函数, 变量用字符串, 函数直接写。 如iphone.num
回调函数( newVal, oldVal )
false/true 深度监听 iphone.money/iphone
)
*/
$scope.$watch($scope.sum,function(newVal,oldVal){
//console.log(newVal);
//console.log(oldVal);
$scope.iphone.fre = newVal >= 100 ? 0 : 10;
});
}
<div ng-controller="Aaa" ng-app>
<p>价格:<input type="text" ng-model="iphone.money"></p>
<p>个数:<input type="text" ng-model="iphone.num"></p>
<p>费用(没有使用函数):<span>{{ iphone.money * iphone.num | currency:'¥' }}</span></p>
<p>费用(使用函数):<span>{{ sum() | currency:'¥' }}</span></p>
<p>运费:<span>{{iphone.fre | currency:'¥'}}</span></p>
<p>总额:<span>{{ sum() + iphone.fre | currency:'¥'}}</span></p>
</div>
发现 –> 复杂交互的时候,非常方便
简单实用5 – 模块化开发
- 减少全局污染
- 模块自动互相依赖
angular.module( 名字, [依赖的其他模块] );
ng-app –> 可以指定哪个模块为初始模块
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.name = 'hello';
}]);
m1.controller('Bbb',['$scope',function($scope){
$scope.name = 'hi';
}]);
/*
链式操作 和 解决压缩后$scope 依赖被解决
angular.module('myApp',[]).controller('xxxx',['$scope', function($scope){
}])
*/
<div ng-controller="Aaa" ng-app="myApp">
<p>{{name}}</p>
</div>
<div ng-controller="Bbb" ng-app="myApp">
<p>{{name}}</p>
</div>
简单使用6 – 工具方法 之1 bind[this指向]、copy[前者覆盖后者]、extend[后者覆盖前者]
- augular.bind()
angular.bind(); -> $.proxy() : 改this指向
function show(n1,n2){
alert(n1);
alert(n2);
alert(this);
}
angular.bind(document,show,3)(4);
- augular.copy()
拷贝对象 --- 前者覆盖后者
var a = {
name : 'hello',
age : 'a'
};
var b = {
age : 'b'
};
var c = angular.copy(a,b); // a把所有值覆盖给了b
console.log(b);
- augular.extend
对象继承 --- 后者覆盖前者
var a = {
name : 'hello',
age : 'a'
};
var b = {
age : '20',
sex : 'b'
};
var c = angular.extend(a,b);
console.log(c == a);
console.log(a);
↓
output:
true
Object {name: "hello", age: "20", sex: "b"}
简单使用7 – 工具方法 之2 identity noop lowercase upparcase
- angular.identity/noop
var str = 'hello';
console.log(angular.identity(str)); //hello
function identity(str){
return str;
}
console.log(angular.noop()); //undefined
function noop(){
}
- lower/uppar case
- augular.element
获取元素 -- 简化版的$
- http://docs.angularjs.cn/api/ng/function/angular.element
<div id="div1" ng-app>aaaaaaaa</div>
<script>
var oDiv = document.getElementById('div1');
angular.element( oDiv ).html('newhtml')
$('#div1').css('background','red');
//angular.element === $
</script>
- angular.bootstrap
动态加载
var m1 = angular.module('myApp1',[]);
var m2 = angular.module('myApp2',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.name = 'hello';
}]);
m2.controller('Bbb',['$scope',function($scope){
$scope.name = 'hi';
}]);
document.onclick = function(){
var aDiv = document.getElementsByTagName('div');
angular.bootstrap(aDiv[0],['myApp1']);
angular.bootstrap(aDiv[1],['myApp2']);
};
<div ng-controller="Aaa">
<p>{{name}}</p>
</div>
<div ng-controller="Bbb">
<p>{{name}}</p>
</div>
注意:
angular.bootstrap( 元素, 【模块】 ) 加入模块 — 原生不可以
好处 : 第三方库和动态创建
简单使用8 — $scope.apply
原生setTimeout来改变某个值
function Aaa($scope,$timeout){
$scope.name = 'hello';
setTimeout(function(){
//$scope.name = 'hi';
$scope.$apply(function(){
$scope.name = 'hi';
});
},2000);
/*$timeout(function(){
$scope.name = 'hi';
},2000);*/
$scope.show = function(){
$scope.name = 'hi';
};
}
直接用$apply来监听变化。
好处: 第三方库,或者jquery
简单使用9 — $scope.module.run
var m1 = angular.module('myApp',[]);
m1.run(['$rootScope',function($rootScope){
$rootScope.name = 'hello';
}]);
<div ng-app="myApp">
<p>{{name}}</p>
</div>
简单使用10 — 详细angular过滤器
- 过滤器扩展部分
- 可组合使用过滤器
- JS中使用过滤器
- angular.module.controller [ ]
- $scope / $rootScope / $timeout
- $filter (过滤器和上面三个一样是”服务”,若要使用,需引入)
- angular.module.controller [ ]
- 自定义过滤器
- angular.module
- controller/run
- filter (拓展的时候用到, filter和上面一样是 module的方法)
- angular.module
var m1 = angular.module('myApp',[]);
/*
angular.module.filter("方法名", function(){
return 函数(参数){
return 值。
}
})
*/
m1.filter('firstUpper',function(){
return function(str,num){
//console.log(num);
return str.charAt(0).toUpperCase() + str.substring(1);
}
});
/*
如果使用,则要引入 $filter
*/
m1.controller('Aaa',['$scope','$filter',function($scope,$filter){
//$scope.name = '723894734.7489545';
//$scope.name = 'hello';
//$scope.name = {"name":"hello","age":"20"};
//$scope.name = ['a','b','c'];
//$scope.name = '3748935795';
/*$scope.name = [
{color:"red",age:"20"},
{color:"yellow",age:"30"},
{color:"blue",age:"40"},
{color:"green",age:"10"}
];*/
//$scope.name = $filter('uppercase')('hello');
//$scope.name = $filter('number')('236478234.3647348',1);
//$scope.name = $filter('date')('236478234','hh');
$scope.name = $filter('firstUpper')('hello');
}]);
<div ng-controller="Aaa">
<!-- <p>{{jine | currency:"¥"}}</p> -->
<!--<p>{{ name | number : 0 : 2 }}</p>-->
<!--<p>{{ name | uppercase }}</p>-->
<!--<pre>{{ name | json }}</pre>-->
<!--<p>{{ name | limitTo : 2 }}</p>-->
<!--<p>{{ name | date : 'yyyy' }}</p>-->
<!--<p>{{ name | orderBy : 'age' : true }}</p>-->
<!--<p>{{ name | filter : 'l' }}</p>-->
<!--<p>{{ name | limitTo : 2 | uppercase }}</p>-->
<!--<p>{{ name | firstUpper : 2 }}</p>-->
<p>{{ name }}</p>
</div>
文档 : 过滤器
自定义过滤去未完成 (未解释)
-过滤器扩展及自定义过滤器
指令
简单使用11 — ng-repeat 的使用
- 已经学过的指令:
- ng-app
- ng-controller
- ng-click
- 作用: 遍历集合
angular.module('myApp',[]).controller('Aaa', ['$scope', function($scope){
$scope.arrList = [
'aaa', 'bbb', 'ccc'
];
}])
<div ng-controller="Aaa">
<ul>
<li ng-repeat=" data in arrList ">{{data}}</li>
</ul>
</div>
output:
aaaaa
bbbbb
cccccc
在 ng-repeat 中操作
表格1:
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$filter',function($scope,$filter){
var oriArr = [
{ name : "red" , age : "20" },
{ name : "yellow" , age : "40" },
{ name : "blue" , age : "30" },
{ name : "green" , age : "10" }
];
}]);
<div ng-controller="Aaa">
<table border="1">
<tr>
<td>年龄</td>
<td>姓名</td>
</tr>
<tr ng-repeat="data in dataList">
<td>{{data['name']}}</td>
<td>{{data.age}}</td>
</tr>
</table>
</div>
增加,排序
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$filter',function($scope,$filter){
var oriArr = [
{ name : "red" , age : "20" },
{ name : "yellow" , age : "40" },
{ name : "blue" , age : "30" },
{ name : "green" , age : "10" }
];
$scope.dataList = oriArr;
/*
排序功能
*/
$scope.fnSort = function(arg){
arguments.callee['fnSort'+arg] = !arguments.callee['fnSort'+arg];
$scope.dataList = $filter('orderBy')($scope.dataList , arg , arguments.callee['fnSort'+arg] );
};
/*
搜索
*/
$scope.fnFilter = function(){
// $scope.dataList = $filter('filter')( $scope.dataList, $scope.filterVal )
// 解决上面重复查询,加了一个变量
$scope.dataList = $filter('filter')( oriArr , $scope.filterVal );
};
}]);
<div ng-controller="Aaa">
<input type="text" ng-model="filterVal"><input type="button" ng-click="fnFilter()" value="搜索">
<table border="1">
<tr>
<th ng-click="fnSort('name')">姓名</th>
<th ng-click="fnSort('age')">年龄</th>
</tr>
<tr ng-repeat="data in dataList">
<td>{{ data.name }}</td>
<td>{{ data.age }}</td>
</tr>
</table>
</div>
简单使用12 — ng-repeat 的扩展使用
- ng-repeat 指令
- 扩展部分
$index
$first
$middle
$last
$even
$odd
ng-repeat-start
ng-repeat-end
- 扩展部分
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.dataList = [
'aaaaa' , 'bbbbb' , 'cccccc' , 'dddddd' , 'eeeeee'
];
}]);
<div ng-controller="Aaa">
<ul>
<li ng-repeat=" data in dataList ">{{$index}}</li>
</ul>
<ul>
<li ng-repeat=" data in dataList ">{{$first}}</li>
</ul>
<ul>
<li ng-repeat=" data in dataList ">{{$last}}</li>
</ul>
<ul>
<li ng-repeat=" data in dataList ">{{$middle}}</li>
</ul>
<ul>
<li ng-repeat=" data in dataList ">{{$even}}</li>
</ul>
<ul>
<li ng-repeat=" data in dataList ">{{$odd}}</li>
</ul>
</div>
隔行变色?
<ul>
<li class="{{ $even ? 'active1' : 'active2' }}" ng-repeat=" data in dataList ">{{ data }}</li>
</ul>
非子循环?
<div ng-repeat-start="data in dataList">{{data}}</div>
<p>{{data}}</p>
<div ng-repeat-end>{{data}}</div>
简单使用12 — 事件指令详解
和原生的相比: 可以动态控制某某属性和变量
- 事件指令
ng-click/dblclick
ng-mousedown/up
ng-mouseenter/leave
ng-mousemove/over/out
ng-keydown/up/press
ng-focus/blur
ng-submit
- 事件指令
ng-selected
ng-change
ng-copy
ng-cut
ng-paste
<div ng-controller="Aaa">
<input type="checkbox" ng-model="aaa">
<select>
<option>11111</option>
<option ng-selected="aaa">22222</option>
</select>
<br>
↑ selected 根据radio来一起用。 效果
<br>
<br>
监听改变:<input type="text" ng-change="bbb='hello'" ng-model="bbb">{{bbb}}<br>
监听复制:
监听剪切:
监听黏贴:<input type="text" value="aasdassssssss" ng-paste="ccc=true">{{ccc}}
</div>
- angularJs的指令
- ng-disabled
- 服务 $interval
- ng-readonly
- ng-checked
- ng-value
- ng-disabled
ng-disabled 倒计时 - 服务 $interval
angular.module('myApp', []).controller('Aaa', ['$scope','$interval',function($scope, $interval){
var iNow = 5;
$scope.text = iNow+"秒"; // $scope 的一个挂载
$scope.isDisabled = true;
// setTimeout -> $scope.$apply
// $timeout -- $interval
// 不要忘记引入
var timer = $interval(function(){
iNow--;
$scope.text = iNow+'秒';
if( iNow == 0 ) {
$scope.text = '可点击';
$scope.isDisabled = false;
$interval.cancel( timer );
}
}, 1000);
}])
<div ng-controller="Aaa">
<input type="button" value="{{text}}" ng-disabled="isDisabled">
<!-- <button ng-click="countDown" ng-disabled="isDisabled">{{text}}</button> -->
</div>
为什么用ng-text? 而不用txt?
{{text}} 用户体验
数据显示优化处理及插件简介
- angularJs的指令
- ng-bind
- ng-cloak
- ng-bind-template
- ng-bind-html
- ng-non-bindable
提高一下用户体验
<script src="angular.min.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.3.0-beta.13/angular-sanitize.min.js"></script>
var m1 = angular.module('myApp',['ngSanitize']);
m1.controller('Aaa',['$scope',function($scope){
$scope.text = '<h1>hello</h1>';
}]);
<div ng-controller="Aaa">
<div ng-bind="text"></div>
<div ng-bind-template="{{text}},{{text}}"></div>
<div ng-bind-html="text"></div>
<div ng-cloak>{{text}}</div>
<div ng-non-bindable>{{text}}</div>
<!-- 因为non-bindable插件没有引入,所以没有出来效果 -->
<!-- 未加载完时,display: none -->
</div>
<script>
alert(1);
</script>
指令1
- angularJs的指令
- ng-class
- ng-style
- ng-href
- ng-src
- ng-attr-(suffix)
<style>
.red{ background:red;}
.yellow{ background:yellow;}
</style>
var m1 = angular.module('myApp',[]).controller('Aaa',['$scope',function($scope){
$scope.text = 'hello';
$scope.style = "{color:'red',background:'yellow'}";
$scope.sClass = "{red:true,yellow:true}";
$scope.url = "http://www.baidu.com";
}]);
<div ng-controller="Aaa">
<div ng-class="{red:true, yellow:false}">{{text}}</div>
<div ng-class="{{sClass}}">{{text}}</div>
<div ng-style="{background: 'gray', fontSize:'14px'}">{{text}}</div>
<div ng-style="{{style}}">{{text}}</div>
<!-- ng-href ng-src .... -->
<a ng-href="{{url}}">aaaaaaa</a>
<!-- ng-attr-(suffix) suffix: 属性名 -->
<a ng-attr-href="{{url}}" ng-attr-title="{{text}}" ng-attr-class="" ng-attr-style="">aaaaaaa</a>
</div>
指令2
- angularJs的指令
- ng-show
- ng-hide
- ng-if
- ng-swtich
- on
- default
- when
- ng-open
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.bBtn = true;
}]);
<div ng-controller="Aaa">
<input type="checkbox" ng-model="bBtn">
<!-- <div ng-show="bBtn">aaaaa show</div>
<div ng-hide="bBtn">bbbbb hide</div>
dom的添加删除
<div ng-if="bBtn"></div> -->
<!-- 其实是switch -->
<!-- <div ng-switch on="bBtn">
<p ng-switch-default>显示的效果</p>
<p ng-switch-when="false">切换的效果</p>
</div> -->
<details ng-open="bBtn">
<summary>Copyright 2011.</summary>
<p>All pages and graphics on this web site are the property of W3School.</p>
</details>
</div>
指令3
- angularJs的指令
- ng-init
- ng-include
- ng-model
- ng-model-options
- updateOn
- ng-controller
- as
尽量不用 ng-init
初始化数据:
特殊情况:
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
//$scope.text = 'hello';
$scope.arr = [['a','b'],['c','d']];
}]);
<div ng-controller="Aaa">
<div ng-repeat="arrOuter in arr" ng-init="outerIndex = $index">
<div ng-repeat="arrInner in arrOuter" ng-init="innerIndex = $index">
<p>{{arrInner}}:{{outerIndex}}{{innerIndex}}</p>
</div>
</div>
</div>
- 一个input,双绑,当光标移出后才改变数据。
- ng-model-options
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.text = 'hello';
}]);
<div ng-controller="Aaa">
<input type="text" ng-model="text" ng-model-options="{updateOn : 'blur'}">
<div>{{text}}</div>
</div>
用面向对象来搞↑
- as
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',FnAaa]);
function FnAaa($scope){
}
FnAaa.prototype.num = '123';
FnAaa.prototype.text = 'hello';
FnAaa.prototype.show = function(){
return 'angularJS';
};
<div ng-controller="FnAaa as a1">
<div>{{a1.text}}:{{a1.show()}}</div>
</div>
标签指令详解
对原有的标签来升级。
- a
- select
- ng-options
- for in
- ng-options
- textarea
- input
- form
- novalidate
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.colors = [
{ name : 'red' },
{ name : 'yellow' },
{ name : 'blue' }
];
}]);
<div ng-app="myApp" ng-controller="Aaa">
<a href="">里面的密友默认刷新 -- {{myColor}} </a>
<br>
<select ng-options=" color.name for color in colors " ng-model="myColor">
</select>
<form action="?" novalidate >
<input type="email">
<input type="submit">
</form>
<br>
</div>
<a href="">外面的友默认刷新</a>
结合表单验证最好, 但先了解form标签
- angularJs的表单验证
- $valid
- $invalid
- $pristine
- $dirty
- $error
- 注意点
- name的方式进行查找
- 要写ng-model
- class
- .ng-valid{}
- .ng-invalid{}
- .ng-pristine{}
- .ng-dirty{}
input.ng-valid{background:green;}
input.ng-invalid{background:red;}
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.text = 'hello';
}]);
<div ng-controller="Aaa">
<form novalidate name="myForm">
<input
type="text"
name="myText"
ng-model="text"
required
ng-minlength="5"
ng-pattern="/^[a-zA-Z]+$/">
<div>{{ myForm.myText.$valid }}</div>
<div>{{ myForm.myText.$invalid }}</div>
<div>{{ myForm.myText.$pristine }}</div>
<div>{{ myForm.myText.$dirty }}</div>
<div>{{ myForm.myText.$error }}</div>
</form>
</div>
表单验证实例&应用
- 实例
实战中的表单验证方式 ↓
angular.module('myApp', []).controller('Aaa', ['$scope',function($scope){
$scope.regText = {
regVal : 'default',
regList : [
{ name : 'default', tips : '请输入' },
{ name : 'required', tips : '需非空' },
{ name : 'pattern', tips : '需字母' },
{ name : 'pass', tips : 'dui' },
],
// change : function(err){
// for( var attr in err ){
// if(err[attr] == true ) {
// this.regVal = attr;
// return ;
// }
// }
// this.regVal = 'pass';
// }
}
$scope.regPassword = {
regVal : 'default',
regList : [
{ name : 'default', tips : '请输入' },
{ name : 'required', tips : '需非空' },
{ name : 'minlength', tips : '最小长度6' },
{ name : 'pass', tips : 'dui' },
],
// change: function(err){
// for( var attr in err ){
// if(err[attr] == true ) {
// this.regVal = attr;
// return ;
// }
// }
// this.regVal = 'pass';
// }
}
$scope.change = function(err, re){
for( var attr in err ){
if(err[attr] == true ) {
// this.regVal = attr;
$scope[re].regVal = attr;
return ;
}
}
this.regVal = 'pass';
}
}])
<div ng-controller="Aaa">
<form action="" name="nForm" >
<div>
<label>用户名</label>
<input type="text" name="nText" ng-model="regText.name" required ng-pattern="/^[a-zA-Z]+$/" ng-blur="change( nForm.nText.$error, 'regText' )">
<span ng-repeat=" re in regText.regList | filter : regText.regVal " >{{re.tips}}</span>
</div>
<div>
<label>密码</label>
<input type="password" name="nPassword" ng-model="regPassword.name" required ng-minlength="6" ng-blur="change( nForm.nPassword.$error, 'regPassword' )">
<span ng-repeat=" re in regPassword.regList | filter : regPassword.regVal " >{{re.tips}}</span>
</div>
</form>
</div>
注意:
- 各个input带上ng-model挂载 双绑
- 各个调用通过name来索引
- ng-blur
- 注意带上的class,可以根据class来写出 #xxx.ng-valid{} 的选择器
- 如果能统一的思想最好。
- 论filter的重要性
自定义指令
- angularJs的自定义指令
- angular.module
controller 控制器
run 初始操作
filter 过滤器
- directive –> 自定义!!!
- restrict的四种定义方式
- replace
- template
- templateUrl
- angular.module
angular.module('myApp', [
]).directive('myHello', function(){
return {
// restrict:'E', // -> <hello></hello>
// restrict:'A', // -> <p hello></p>
// restrict:'AE', // -> <hello></hello> <p hello></p>
// restrict:'AEC', // -> <hello></hello> <p hello></p>
restrict:'AECM', // -> <hello></hello> <p hello></p>
template:'<div> template </div>',
replace: true, // 替换模板
};
}).controller('Aaa', ['$scope',function($scope){
}])
<!-- 模板替代 ↓ -->
<my-hello></my-hello>
<!-- 功能性 ↓ -->
<p my-hello></p>
后两种用的少
<p class="hello"></p>
<!-- direcitive:hello -->
directive指令扩展 — 选项卡
引入模板
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 div{ width:200px; height:200px; border:1px red solid; display:none;}
#div1 input.active{ background:red;}
</style>
<script src="angular.min.js"></script>
<script>
angular.module('myApp', [
]).directive('myTab', function(){
return {
restrict:'E',
replace: true,
/*template:'\
<div id="div1">\
<input class="active" type="button" value="1">\
<input type="button" value="2">\
<input type="button" value="3">\
<div style="display:block">11111111</div>\
<div>22222222</div>\
<div>33333333</div>\
</div>', */
templateUrl:'test2.html',
};
});
// 如果html较多, 通过引入 templateUrl 结局。
</script>
</head>
<body>
<my-tab></my-tab>
<!-- <div id="div1">
<input class="active" type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<div style="display:block">11111111</div>
<div>22222222</div>
<div>33333333</div>
</div> -->
</body>
</html>
作用域
- angularJs的自定义指令
- directive
- scope
- 独立作用域true
- 隔离作用域{}
- @
- =
- &
选项卡框架的搭建
test2.html :
<div id="{{myId}}">
<input class="active" type="button" value="1" ng-click="myFn({num:456})">
<input type="button" value="2">
<input type="button" value="3">
<div style="display:block">{{myName}}</div>
<div>22222222</div>
<div>33333333</div>
</div>
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 div, #div2 div{ width:200px; height:200px; border:1px red solid; display:none;}
#div1 input.active, #div2 input.active{ background:red;}
</style>
<script src="angular.min.js"></script>
<script>
angular.module('myApp', [
]).directive('myTab', function(){
return {
restrict:'E',
replace: true,
templateUrl:'test2.html',
// scope: true, // 独立作用域 ↓
scope : {
// 活数据,可以通过这种方式来搞
// myId: '@', 模板页( my-id="xxx" ) 可以用
myId: '@aaa',
myName: '=',
myFn: '&'
}, // 隔离作用域 , 如果这样,怎么传入数据? ↓
controller: ['$scope', function($scope){
// 死()数据,放在controller
$scope.name = "miao";
}],// return范围内的
};
}).controller('Aaa', ['$scope', function($scope){
$scope.name = "~hello~";
$scope.show = function(num){
alert(num);
}
}])
</script>
</head>
<pre>
@ 和 = 区别:
@ 就是绑定的一个字符串
= 就不是字符串了,是变量数据了。
& 函数传递
</pre>
<body ng-controller="Aaa">
<my-tab aaa="div1" my-name="name" my-fn="show(num)"></my-tab>
<my-tab aaa="div2" my-name="name" my-fn="show(num)" ng-init="name='hi'"></my-tab>
</body>
</html>
选项卡内容的完善
- link
- scope
- element
- attr
- reController
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 div, #div2 div{ width:200px; height:200px; border:1px red solid; display:none;}
#div1 input.active, #div2 input.active{ background:red;}
</style>
<script src="jquery.js"></script>
<script src="angular.min.js"></script>
<script>
angular.module('myApp', [
]).directive('myTab', function(){
return {
restrict:'E',
replace: true,
scope : {
myId: '@aaa',
myData: '='
},
controller: ['$scope', function($scope){
$scope.name = "miao";
}],
// templateUrl:'test2.html',
template:'\
<div id="{{myId}}">\
<input ng-repeat="data in myData" type="button" ng-value="data.title" ng-class="{active:$first}">\
<div ng-repeat="data in myData" ng-style="{display:$first? '+'block'+' : '+'none'+'}">{{ data.content }}</div>\
</div>',
// ↓ 就是进行dom操作的
// scope
// element
// attr
// reController
link:function(scope, element, attr){
// console.log( scope.name ); --> miao
// console.log( element ); // --> 父层div
// console.log( attr ); --> 属性 e.g.: attr.myId
// element.css()
// element.delegate 是委托操作
// ↓ 基本的jquery操作
element.delegate('input', 'click', function(){
$(this).attr('class','active').siblings('input').attr('class', '');
$(this).siblings('div').eq( $(this).index() ).css('display', 'block').siblings('div').hide();
});
}
};
}).controller('Aaa', ['$scope', function($scope){
$scope.data1 = [
{title:'数学', content:'111111111'},
{title:'语文', content:'222222222'},
{title:'英语', content:'333333333'}
];
$scope.data2 = [
{title:'物理', content:'444444444'},
{title:'化学', content:'555555555'},
];
}])
</script>
</head>
<body ng-controller="Aaa">
<my-tab aaa="div1" my-data="data1"></my-tab>
<my-tab aaa="div2" my-data="data2"></my-tab>
</body>
</html>
注意:
配合jquery
dom操作放在link中执行
模板的写法,注意数据和 模板的整合。 现在是隔离作用域,绑定策略的方式。
拖拽自定义指令
实现将下面html带上一个 my-drap 就可以拖动的扩展。
<body ng-controller="Aaa">
<div id="div1" my-drap></div>
</body>
第一步-初始化:
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height:100px;background: purple;}
</style>
<script src="jquery.js"></script>
<script src="angular.min.js"></script>
<script>
angular.module('myApp', [
]).directive('myDrag', function(){
return {
restrict:'A', // 既然是属性指令,那就用 A
link:function(scope, element, attr){
console.log( element ); // 拖拽的元素
}
};
}).controller('Aaa', ['$scope', function($scope){
}])
</script>
</head>
<body ng-controller="Aaa">
<div id="div1" my-drap></div>
</body>
</html>
第二步 – 拖拽和可传参数 – 可复用~:
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height:100px;background: purple; position: absolute;}
</style>
<script src="jquery.js"></script>
<script src="angular.min.js"></script>
<script>
angular.module('myApp', [
]).directive('myDrag', function(){
return {
restrict:'A', // 既然是属性指令,那就用 A
link:function(scope, element, attr){
var disX = 0;
var disY = 0;
// 第三个参数拿到值
// string 类型改bool
// console.log( angular.equals(attr.myDrag) ); 判断两个值是否相等。
var myDrag = angular.equals(attr.myDrag, 'true');
console.log( myDrag );
element.on('mousedown', function( ev ){
var This = this;
disX = ev.pageX - $(this).offset().left;
disY = ev.pageY - $(this).offset().top;
console.log( $(this).outerWidth() );
// ↓ 虚线框
if( myDrag ){
var $line = $('<div></div>');
$line.css({
width: $(this).outerWidth()+'px',
height: $(this).outerHeight()+'px',
position: 'absolute',
left: $(this).offset().left+'px',
top: $(this).offset().top+'px',
border: '1px dotted gray',
zIndex:'-1',
})
$('body').append($line);
}
$(document).on('mousemove', function(ev){
$(This).css('left', ev.pageX - disX);
$(This).css('top', ev.pageY - disY);
})
$(document).on('mouseup', function(){
if( myDrag ){
$(This).css({
'left': $line.offset().left,
'top': $line.offset().top,
})
$line.remove();
}
$(document).off();
})
return false;
})
}
};
}).controller('Aaa', ['$scope', function($scope){
}])
</script>
</head>
<body ng-controller="Aaa">
<div id="div1" my-drag="true"></div>
</body>
</html>
指令如果嵌套?
<hello>
<hi></hi>
</hello>
angular.module('myApp', [
]).directive('hello', function(){
return {
restrict:'E',
replace: true,
transclude: true,
// ↓ 意思是内部的东西,放在h2中
template: '<div ng-transclude>hello ang <h2 ng-transclude></h2> </div>' //<div ng-transclude>hello ang <h2></h2> </div>
};
}).directive('hi', function(){
return {
restrict:'E',
replace: true,
template: '<span>hi ang</span>'
};
}).controller('Aaa', ['$scope', function($scope){
}])
交互( 数据传递 ):
angular.module('myApp', [
]).directive('hello', function(){
return {
restrict:'E',
replace: true,
transclude: true,
// ↓ 意思是内部的东西,放在h2中
template: '<div ng-transclude>hello ang <h2 ng-transclude></h2> </div>', //<div ng-transclude>hello ang <h2></h2> </div>
controller: function( $scope ){
// $scope.name = "miao"; 不可用
this.name = 'miao';
}
};
}).directive('hi', function(){
return {
restrict:'E',
replace: true,
template: '<span>hi ang</span>',
require: '^hello', // 引入hello配置 ?容错 ^父级 空,当前
link: function(scope, element, attr, reController){
// reController 所依赖的controller对象。
console.log( reController.name ); // require --> 要带 "^" 父级
}
};
}).controller('Aaa', ['$scope', function($scope){
}])
$http服务
已经:
- angularJs的服务
- $scope
- $watch
- $apply
- $rootScope
- $timeout
- $interval
- $filter
$http
- method
- url
- success
- error
- 简写方式
- jsonp
- JSON_CALLBACK
- 例子 : 百度下拉搜索
类似于jquery的ajax
angular.module('myApp', [
]).controller('Aaa', ['$scope', '$http', function($scope, $http){
$http({
method: 'GET',
url: 'index.php',
}).success(function(data, state, headers, config){
console.log( data );
console.log( state );
console.log( headers );
console.log( config );
}).error(function(data){
console.log( data );
})
$http.get('index.php').success(function(data){ })
}])
$location服务
- angularJs的服务
- $location
- absUrl()
- path()
- replace()
- hash()
- search()
- url()
- host()
- port()
- protocol()
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$location',function($scope,$location){
var a =$location;
// http://localhost/test.html?/aaa/#/fds/bbb
console.log( 'absUrl(): ' + a.absUrl() );
// /fds/bbb
console.log( 'path(): ' + a.path() ); // -> 路由操作
$location.path('aaa/bbb/ccc').replace();
$location.hash('heelo');
$location.search({'age':20});
console.log( 'url(): ' + a.url() );
console.log( 'host(): ' + a.host() );
console.log( 'port(): ' + a.port() );
console.log( 'protocol(): ' + a.protocol() );
}]);
$anchorScroll
锚点跳转
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$location','$anchorScroll',function($scope,$location,$anchorScroll){
$scope.change = function( id ){
// 引入 anchorScroll 自动跳转了
// hash 相同时,不会跳转
console.log( id )
$location.hash( id );
$anchorScroll(id)
}
}]);
<body ng-controller="Aaa">
<ul>
<li ng-repeat="i in [1,2,3,4,5]" ng-click="change('div'+i)">{{i}}-------------------------------aaaa</li>
</ul>
<div ng-repeat="i in [1,2,3,4,5]" ng-attr-id="div{{i}}">{{i}}</div>
</body>
- $cacheFactory 缓存
- info()
- put()
- get()
- remove()
- 配置capacity
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$cacheFactory',function($scope,$cacheFactory){
/*
名字 , 限定缓存长度
*/
var cache = $cacheFactory('myCache', {capacity:1});
cache.put( 'name', 'hello' );
cache.put( 'age', '20' );
cache.remove('age')
console.log( cache.info() );
console.log( cache.get('name') );
}]);
$log服务 — 封装了console.log
$interpolate 插值服务
- 就是将textarea里面的{{xx}}解析
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
div {width: 200px; height:300px; border: 3px solid gray;margin-top: 10px; }
ul{ position: fixed; right: 0px; top: 0px;}
</style>
<script src="jquery.js"></script>
<script src="angular.min.js"></script>
<script>
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$interpolate',function($scope,$interpolate){
$scope.$watch('body',function(newVal){
if( newVal ){
var temp = $interpolate(newVal);
$scope.showText = temp({ name : $scope.name });
}
})
}]);
</script>
</head>
<body ng-controller="Aaa">
<input type="text" ng-model="name">
<textarea ng-model="body"></textarea>
<p>{{showText}}</p>
</body>
</html>
$q 服务 — 延迟对象
- $q
- promise的实现
- defer()
- resolve()
- reject()
- notify()
- then()
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope','$q',function($scope,$q){
var dfd = $q.defer();
function show(){
setTimeout(function(){
dfd.resolve();
dfd.reject();
}, 2000);
return dfd.promise;
}
show.then(function(){
alert('陈宫');
}, function(){
alert('失败');
})
}]);
供应商概念 $provider — 封装的factory
服务的相关初始操作
<script>
var m1 = angular.module('myApp',[]);
// m1.config(['$scopeProvider'])
m1.config(['$interpolateProvider',function($interpolateProvider){
$interpolateProvider.startSymbol('@@');
$interpolateProvider.endSymbol('@@');
}]);
m1.controller('Aaa',['$scope','$interpolate',function($scope,$interpolate){
$scope.showText = '~~~~~~~~~';
}]);
</script>
</head>
<body ng-controller="Aaa">
<p>@@showText@@</p>
</body>
debug开关
var m1 = angular.module('myApp',[]);
m1.config(['$interpolateProvider','$logProvider',function($interpolateProvider,$logProvider){
$logProvider.debugEnabled(false);
}]);
m1.controller('Aaa',['$scope','$log',function($scope,$log){
$log.debug('hello');
}]);
禁止自动跳转
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#parent div{ width:300px; height:500px; border:1px #000 solid; margin:20px;}
#parent ul{ width:200px; position:fixed; top:0; right:0;}
</style>
<script src="angular.min.js"></script>
<script>
var m1 = angular.module('myApp',[]);
m1.config(['$anchorScrollProvider',function($anchorScrollProvider){
$anchorScrollProvider.disableAutoScrolling();
}]);
m1.controller('Aaa',['$scope','$location','$anchorScroll',function($scope,$location,$anchorScroll){
$scope.change = function(id){
$location.hash(id);
$anchorScroll(); // 手动调用, 禁止自动跳转
};
}]);
</script>
</head>
<body>
<div id="parent" ng-controller="Aaa">
<ul>
<li ng-repeat="id in [1,2,3,4,5]" ng-click="change('div'+id)">{{id}}aaaaaaaaaa</li>
</ul>
<div ng-repeat="id in [1,2,3,4,5]" ng-attr-id="div{{id}}">{{id}}</div>
</div>
</body>
</html>
自定义服务 provider - - factory
框架
var m1 = angular.module('myApp',[]);
m1.factory('myService',[function(){
return {
name: 'hello',
show: function(){
return this.name + ':angular'
}
}
}])
m1.controller('Aaa',['$scope','myService',function($scope,myService){
console.log( myService.show() );
}]);
随机数
m1.factory('myRandomNum',function(){
return function(num1,num2){
return Math.random()*(num2 - num1) + num1;
};
});
m1.controller('Aaa',['$scope','myRandomNum',function($scope,myRandomNum){
console.log( myRandomNum(-3,6) );
}]);
factory 和 provider , factory最终还是会去调用provider
/*m1.factory('myService',function(){
return {
name : 'hello',
show : function(){
return this.name + ':angular';
}
};
});*/
m1.provider('myService',function(){
return {
name : 'hello',
$get : function(){
return {
name : this.name,
show : function(){
return this.name + ':angular';
}
};
}
};
});
m1.config(['myServiceProvider',function(myServiceProvider){
console.log(myServiceProvider);
myServiceProvider.name = 'hi';
}]);
m1.controller('Aaa',['$scope','myService',function($scope,myService){
console.log(myService.show());
}]);
用provider来实现,配置可取整的随机数
m1.provider('myRandomNum', function(){
return {
isInt: false,
int: function(argBol){
if(argBol){
this.isInt = true;
}else{
this.isInt = false;
}
},
$get: function(){
var This = this;
return function(num1, num2){
return This.isInt ? Math.round(Math.random()*(num2 - num1)) + num1 : Math.random()*(num2 - num1) + num1;
}
}
}
})
m1.config(['myRandomNumProvider',function(myRandomNumProvider){
myRandomNumProvider.int(false);
}]);
m1.controller('Aaa',['$scope','myRandomNum',function($scope,myRandomNum){
console.log( myRandomNum(-3,6) );
}]);
模块间的通信
先看模块通信, 再看provider的好处。
var m1 = angular.module('module1',[]);
m1.factory('myService',function(){
return {
name : 'hello',
show : function(){
return this.name + ':angular';
}
};
});
var m2 = angular.module('myApp',['module1']);
m2.controller('Aaa',['$scope','myService',function($scope,myService){
console.log(myService.show());
}]);
通过通信,来做一个类似对象的东西。
- server.js
provider
// JavaScript Document
var m1 = angular.module('module1',[]);
/*m1.factory('myService',function(){
return {
name : 'hello',
show : function(){
return this.name + ':angular';
}
};
});*/
m1.provider('myService',function(){
return {
name : 'hello',
$get : function(){
return {
name : this.name,
show : function(){
return this.name + ':angular';
}
};
}
};
});
html1 初始化
var m2 = angular.module('myApp',['module1']);
m1.config(['myServiceProvider',function(myServiceProvider){
myServiceProvider.name = 'hi';
}]);
m2.controller('Aaa',['$scope','myService',function($scope,myService){
console.log(myService.show());
}]);
html2 没有做初始化
var m2 = angular.module('myApp',['module1']);
m2.controller('Aaa',['$scope','myService',function($scope,myService){
console.log(myService.show());
}]);
- 自定义服务 - service()
var m1 = angular.module('myApp', []);
m1.service('myService', FnService)
function FnService(){
this.name = "~";
}
FnService.prototype.age = 20;
m1.controller('Aaa',['$scope', 'myService', function($scope, myService){
console.log( myService.name );
console.log( myService.age );
}])
- -常量 constant & value
var m1 = angular.module('myApp',[]);
m1.constant('myService','hello angular'); /// 可配置
//m1.value('myService','hello angular'); 不可配置
m1.config(['myService',function(myService){
console.log(myService);
}]);
m1.controller('Aaa',['$scope','myService',function($scope,myService){
console.log(myService);
}]);
插件使用 — ngRoute
· 单页面的路由操作
- 真喵的好用
<body ng-controller="Aaa">
<a href="#aaa">首页</a>
<a href="#bbb">学员</a>
<a href="#ccc">课程</a>
<div ng-view></div>
</body>
var m1 = angular.module('myApp', ['ngRoute']);
m1.config(['$routeProvider', function($routeProvider){
// 地址, 配置
$routeProvider.when('/aaa', {
template : '<p>aaaaa</p>', // 或者直接用templateUrl
});
$routeProvider.when('/bbb', {
template : '<p>bb内容</p>',
});
$routeProvider.when('/ccc', {
template : '<p>cc内容</p>',
});
}])
m1.controller('Aaa',['$scope', function($scope){
}])
问题: 初始化时没有路由, 作用域, 绑定事件
<body ng-controller="Aaa">
<a href="#aaa">首页</a>
<a href="#aaa/123">首页/123</a>
<a href="#bbb">学员</a>
<a href="" ng-click="$location.path('/ccc')">课程</a>
<div ng-view></div>
</body>
var m1 = angular.module('myApp', ['ngRoute']);
m1.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/aaa/:num', {
template : '<p>aaaaa</p>{{name}}',
controller:'Aaa'
}).when('/bbb', {
template : '<p>bb内容</p>{{name}}',
controller: 'Bbb', // 作用域问题
}).when('/ccc', {
template : '<p>cc内容</p>{{name}}',
controller: 'Ccc',
}).otherwise({
redirectTo : '/aaa'
});
}])
// 路由事件操作
m1.run(['$rootScope', function($rootScope){
$rootScope.$on('$routeChangeStart', function(event, current, pre){
console.log(event);
console.log(current);
console.log(pre);
})
}])
m1.controller('Aaa',['$scope', '$location', '$routeParams', function($scope, $location, $routeParams){
// 如果作用域问题?
$scope.name = "hello";
$scope.$location = $location;
// 地址传参?
console.log( $routeParams );
}])
m1.controller('Bbb',['$scope', '$location', function($scope, $location){
$scope.name = "hello ~ bbb";
$scope.$location = $location;
}])
// $location 服务和路由配合使用
m1.controller('Ccc',['$scope', '$location', function($scope, $location){
$scope.name = "hello ~ ccc";
$scope.$location = $location;
}])
事件内部传播方式?
↑ run 里面绑定,怎么搞的??
- angularJs的事件
- $emit 向上传播,类似冒泡
- $broadcast 类似捕获
- event
- targetScope
- currentScope
- name
- stopPropagation()
- 内部传播方式
- $routeChangeStart 向下,
- $viewContentLoaded 比如ng-view 发生变化后,向上走
var m1 = angular.module('myApp',[]);
m1.controller('Aaa',['$scope',function($scope){
$scope.count = 0;
$scope.$on('myEvent',function(event){
$scope.count++;
console.log( event.targetScope == event.currentScope );
console.log(event.name);
event.stopPropagation();
});
}]);
<div ng-controller="Aaa">
{{count}}
<div ng-controller="Aaa" ng-click="$broadcast('myEvent')">
{{count}}
<div ng-controller="Aaa">
{{count}}
</div>
</div>
</div>
动画插件
- angularJs的插件
- ngAnimate
- CSS3的方式
- ng-enter
进入
- ng-enter-active
- ng-leave
离开
- ng-leave-active
- 支持的指令
- if,view,repeat,include,swtich
- repeat
- ng-enter-stagger
- animation-delay
<style>
.box{ width:200px; height:200px; background:red; transition:1s all;}
.box.ng-enter{ opacity:0;}
.box.ng-enter-active{ opacity:1;}
.box.ng-leave{ opacity:1;}
.box.ng-leave-active{ opacity:0;}
</style>
var m1 = angular.module('myApp',['ngAnimate']);
m1.controller('Aaa',['$scope',function($scope){
$scope.bBtn = true;
}]);
<div ng-controller="Aaa">
<input type="checkbox" ng-model="bBtn">
<div ng-if="bBtn" class="box"></div>
</div>
运动 & hash & 单页面
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
.box{transition: all 1s; position: absolute;}
.box.ng-enter{ opacity: 0; }
.box.ng-enter-active{ opacity: 1; }
.box.ng-leave{ opacity: 1; }
.box.ng-leave-active{ opacity: 0; }
</style>
<script src="angular.min.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.2.9/angular-route.min.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.2.9/angular-animate.min.js"></script>
<script>
var m1 = angular.module('myApp', ['ngRoute', 'ngAnimate']);
m1.config(['$routeProvider',function($routeProvider){
$routeProvider
.when('/aaa',{
template : '<p>首页的内容</p>{{name}}',
controller : 'Aaa'
})
.when('/bbb',{
template : '<p>学员的内容</p>{{name}}',
controller : 'Bbb'
})
.when('/ccc',{
template : '<p>课程的内容</p>{{name}}',
controller : 'Ccc'
})
.otherwise({
redirectTo : '/aaa'
});
}]);
m1.controller('Aaa',['$scope','$location','$routeParams',function($scope,$location,$routeParams){
$scope.name = 'hello';
$scope.$location = $location;
console.log( $routeParams );
}]);
m1.controller('Bbb',['$scope',function($scope){
$scope.name = 'hi';
}]);
m1.controller('Ccc',['$scope',function($scope){
$scope.name = '你好';
}]);
</script>
</head>
<body ng-controller="Aaa">
<a href="" ng-click="$location.path('aaa')">首页</a>
<a href="" ng-click="$location.path('bbb')">学员</a>
<a href="" ng-click="$location.path('ccc')">课程</a>
<div class="box" ng-view></div>
</body>
</html>
var m1 = angular.module('myApp', ['ngRoute', 'ngAnimate']); 注意引入
ng-repeat 延迟带动画
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
.box{transition: all 1s;}
.box.ng-enter{ opacity: 0; }
.box.ng-enter-active{ opacity: 1; }
.box.ng-leave{ display: none; }
.box.ng-enter-stagger{
animation-delay : 100ms;
}
/*.box.ng-leave-active{ opacity: 0; }*/
</style>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.min.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular-animate.min.js"></script>
<script>
var m1 = angular.module('myApp', ['ngAnimate']);
m1.controller('Aaa',['$scope', '$http', '$timeout', function($scope,$http,$timeout){
$scope.dataList = ['123','312'];
$scope.timer = ''
$scope.change = function(){
$timeout.cancel( $scope.timer );
$scope.timer = $timeout(function(){
$http({
method : 'JSONP',
url : 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+$scope.search+'&cb=JSON_CALLBACK'
}).success(function(data){
$scope.dataList = data.s;
});
}, 300)
}
}])
</script>
</head>
<body ng-controller="Aaa">
<input type="text" ng-model="search" ng-keyup="change(name)">
{{search}}
<ul>
<li class="box" ng-repeat="d in dataList">{{d}}</li>
</ul>
</body>
</html>
注意: .box.ng-enter-stagger {} 延迟
针对样式的css
- angularJs的插件
- ngAnimate
- ng-hide-add
- ng-hide-add-active
- ng-hide-remove
- ng-hide-remove-active
- 支持的指令
- class,show,hide,model等
- JS方式
- animation()
- enter/leave
- removeClass/addClass
- ngAnimate
.box{transition: all 1s; width: 100px; height: 100px; background: purple;}
.box.ng-hide-add{ opacity: 1; }
.box.ng-hide-add-active{ opacity: 0; }
.box.ng-hide-remove{ opacity: 0; }
.box.ng-hide-remove-active{ opacity: 1; }
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.min.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular-animate.min.js"></script>
var m1 = angular.module('myApp', ['ngAnimate']);
m1.controller('Aaa',['$scope', function($scope){
}])
<body ng-controller="Aaa">
<input type="checkbox" ng-model="bBtn">
<div ng-show="bBtn" class="box"></div>
</body>
js的运动控制
enter/leaver
addClass /removeClass
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
.box{ width:200px; height:200px; background:red;}
</style>
<script src="jquery-1.11.1.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.min.js"></script>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular-animate.min.js"></script>
<script>
var m1 = angular.module('myApp',['ngAnimate']);
m1.animation('.box',function(){
return {
addClass : function(element,sClass,done){
//console.log(element);
//console.log(sClass);
//console.log(done);
$(element).animate({width:0,height:0},1000,done);
},
removeClass : function(element,sClass,done){
$(element).css({width:0,height:0});
$(element).animate({width:200,height:200},1000,done);
}
};
});
m1.controller('Aaa',['$scope',function($scope){
$scope.bBtn = true;
}]);
</script>
</head>
<body>
<div ng-controller="Aaa">
<input type="checkbox" ng-model="bBtn">
<!--<div ng-if="bBtn" class="box"></div>-->
<div ng-show="bBtn" class="box"></div>
</div>
</body>
</html>
ngResourec – 前后端交互大的
- angularJs的插件
- ngResource
- 支持 RESTful 架构模式 –
本来是客户端的交互模式,延伸到web
- get()
- query()
- 区别
- save()
- delete()
- 支持 RESTful 架构模式 –
- ngResource