码迷,mamicode.com
首页 > Web开发 > 详细

angularjs介绍

时间:2015-04-22 20:11:18      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:

由来
AngularJS诞生于2009年,由Misko Hevery 等人创建,后为Google所收购。是一款优秀的前端JS框架,已经被用于Google的多款产品当中。AngularJS有着诸多特性,最为核心的是:MVVM、模块化、自动化双向数据绑定、语义化标签、依赖注入,等等。———百度百科
技术分享
 1 <html ng-app ="hello">
 2  
 3 <body>
 4 <div ng-controller = "TextController">
 5 <p >{{someText}}</p>
 6 </div>
 7  
 8  
 9 <div ng-controller ="InputCtrl">
10 <input type="text" ng-model=‘user.name‘ />
11 <input type="text" ng-model=‘user.last‘ />
12 <span>{{user}}</span>
13 </div>
14  
15 <script type="text/javascript" src="script/angular.min.js"></script>
16 <script type="text/javascript">
17 angular.module(hello,[]).controller(TextController, function($scope) {
18 $scope.someText = "Hello World";
19 });
20  
21 function InputCtrl($scope){
22  $scope.user= {name: guest, last: visitor};
23 }
24 </script>
25 </body>
26 </html>
View Code

 

angularjs
常用指令
ng-app、 ng-init 、 ng-model 、 ng-repeat、ng-disabled、ng-show、ng-hide
事件指令
ng-click、ng-dbl-click、ng-mousedown、ng-mouseup、ng-mouseenter、ng-mouseleave、ng-mousemove、ng-mouseover、ng-keydown、ng-keyup、ng-keypress、ng-change
 
ng-repeat
 1 <html>
 2 <head>
 3 <title>repeat</title>
 4 <style type="text/css">
 5 .selected{background:lightgreen;}
 6 </style>
 7 <script type="text/javascript" src="../script/angular.min.js"></script>
 8 </head>
 9 <body ng-app="repeatApp" ng-controller="repeatController">
10 <table>
11 <tr><td>Type</td><td>Price</td><td>Count</td><td>totalPrice</td></tr>
12  
13 <tr ng-repeat="item in items" ng-click="selecItem($index)" ng-class="{selected:$index==selectRow}"><td>{{item.type}}:</td><td>{{item.price | currency}}</td><td>{{item.count}}</td><td>{{item.total}}</td></tr>
14  
15 </table>
16  
17 </body>
18 <script type="text/javascript">
19 var arr=[
20 {type:"apple",price:6.3,count:10},
21 {type:"orange",price:8.1,count:5},
22 {type:"egg",price:123,count:6}
23 ];
24 var a = angular.module("repeatApp",[]);
25 function repeatController($scope){
26  
27 $scope.items = arr;
28 angular.forEach($scope.items , function(value, key) {
29   value.total = value.price*value.count;
30 });
31 $scope.selecItem = function(row){
32 $scope.selectRow = row;
33 }
34 window.scope = $scope;
35 }
36 </script>
37 </html> 
38 ng-include
39 <html>
40 <head>
41 <title>include</title>
42 <script type="text/javascript" src="../script/angular.min.js"></script>
43 </head>
44 <body ng-app="myApp">
45 <div ng-include=‘"test"‘></div>
46 </body>
47  
48 <script type="text/ng-template" id="test">
49   This is the content of the template
50 </script>
51 <script type="text/javascript">
52 var myApp = angular.module(myApp, []);
53 </script>
54 </html>

 

内置服务
$http、$ templateCache 、$log、$location 、$cookieStore、$animate、$q
内置方法
bind,bootstrap,copy,element,equals,extend,forEach,fromJson,identity,injector,isArray,isDate,isDefined,isElement,isFunction,isNumber,isObject,isString,isUndefined,lowercase,module,noop,toJson,uppercase 
demo
http:
伪代码:
1 $http.get(‘url‘,{params:{id:5}
2 }).success(function(data,status,headers,config){
3 //success callback
4 }).error(function(data,status,headers,config){
5 //error callback
6 })

 

get/head/post/delete/put/JSONP
 
 1 $http({
 2 method:string,
 3 url:string,
 4 param:obj,
 5 data:string or object,
 6 headers:object,
 7 transformRequest:function transform(data,headersGetter) or an array of functions,
 8 transformRespones:function transform(data,headersGetter) or an array of functions,
 9 cache:boolean or Cache object,
10 timeout:number,
11 withCredentials:boolean
12 })

 

 
demo:
技术分享
 1 <html>
 2 <head>
 3 <title>Time</title>
 4 <style type="text/css">
 5 .selected{background:lightgreen;}
 6 </style>
 7 <script type="text/javascript" src="../script/angular.min.js"></script>
 8 </head>
 9 <body ng-app="myApp" ng-controller="repeatController">
10 <p>date:{{date}}</p>
11 <p>time:{{time}}</p>
12  
13 </body>
14 <script type="text/javascript">
15 angular.module("myApp",[]);
16 function repeatController($scope,$http){
17 $http.jsonp("http://service.100bt.com/PubTimeNow.action?callback=JSON_CALLBACK")
18 .success(function(data,status,headers,config){
19 $scope.date = data.date;
20 $scope.time = data.time;
21 console.log(data,status,headers(),config);
22 })
23 }
24 </script>
25 </html>
26  
27 log:
28 <html>
29 <head>
30 <title>log</title>
31  
32 <script type="text/javascript" src="../script/angular.min.js"></script>
33 </head>
34 <body ng-app="myApp" ng-controller="myController">
35  
36 </body>
37 <script type="text/javascript">
38 var myApp = angular.module(myApp, []);
39 myApp.controller("myController",function($scope,$log){
40 $log.log("xxx");
41 })
View Code

 

/*
log();
Write a log message
 
info();
Write an information message
 
warn();
Write a warning message
 
error();
Write an error message
 
debug();
Write a debug message
*/
</script>
</html>
 
templateCache
技术分享
 1 <html>
 2 <head>
 3 <title>templateCache</title>
 4 <script type="text/javascript" src="../script/angular.min.js"></script>
 5 </head>
 6 <body ng-app="myApp" ng-controller="control">
 7 <div ng-include=" ‘templateId.html‘ "></div>
 8 </body>
 9 <script type="text/javascript">
10 var myApp = angular.module(myApp, []);
11 /*
12 myApp.run(function($templateCache) {
13   $templateCache.put(‘templateId.html‘, ‘This is the content of the template‘);
14   $templateCache.get(‘templateId.html‘);
15 }).controller("control",function(){});
16 */
17 myApp.controller("control",function($scope,$templateCache,$log){
18 $templateCache.put(templateId.html);
19    $templateCache.get(templateId.html);
20 })
21  
22 </script>
23 </html>
View Code

 

templateId.html
<div>xxxxxxxxxxxx</div>
 
$watch 
$watch(watchFn,watchAction,deepWatch)
watchFn:  带有angular表达式或者函数字符串,返回被监控模型的当前值。会执行多次
watchAction: 一个函数或者表达式,watchFn发生变动时调用,返回watchFn的新旧两个值,和作用域的引用。function(newValue,oldValue,scope)
deepWatch:  设置了true则会去检查被监控对象的每个属性是否发生了变化。如果要监控数组中的元素,或者对象上的全部属性,而不是一个简单的值,就可以使用这个参数。 
 
技术分享
 1 <html ng-app ="storeData">
 2  
 3  
 4 <body>
 5  
 6 <div ng-controller ="InputCtrl">
 7 <div><button ng-click="toggleShow()">toggleData</button><input type="text" ng-model=‘newData‘ ng-keypress="createOnEnter($event)" placeholder="What needs to be done?" /></div>
 8 <ul ng-show="showMe">
 9 <li ng-repeat="item in storeData track by $index" ng-mouseover="showBtn($index)">{{item}}<button ng-show="$index==selectRow" ng-click="remove($index)">removeThis</button></li>
10 </ul>
11 <div>{{count}}ItemLeft</div>
12 </div>
13  
14  
15 <script type="text/javascript" src="script/angular.min.js"></script>
16 <script type="text/javascript">
17  
18 var aaa=angular.module("storeData",[])
19 .controller("InputCtrl",function($scope){
20 $scope.storeData = [];
21 $scope.count;
22 $scope.showMe = true;
23 var activeData = [],allData = [],removeData = [],count=0;
24  
25 $scope.toggleShow = function(){
26 $scope.showMe =!$scope.showMe ;
27 };
28 $scope.showBtn = function($index){
29 $scope.selectRow = $index;
30 };
31 $scope.createOnEnter = function($event){
32 if($event.keyCode ==13){
33 allData.push($scope.newData);
34 activeData.push($scope.newData);
35 $scope.newData="";
36 }
37 }
38 $scope.remove = function(index){
39 var d = allData.splice(index,1);
40 removeData.push(d);
41 }
42 $scope.storeData = allData;
43 $scope.count = count;
44  
45  
46 function calculateCount(newValue,oldValue,scope){
47 console.log(1);
48 console.log(newValue,oldValue);
49 $scope.count=newValue.length;
50 }
51 $scope.$watch(function(){return $scope.storeData},calculateCount,true);
52  
53 })
54 </script>
55 </body>
56 </html>
57  
View Code

 

Module  
controller
第一种:通过方法名声明依赖
 function mycontroller($scroper,$time){};
第二种:声明一个数组,依赖列表放前部,注入目标数组放最后
 var mycontroller = [‘$scope’,’$time’,function($scope,$time){}];
第三种:通过inject属性声明依赖列表
  var mycontroller = function($scope,$time){};
 mycontroller.$inject = [‘$scope’,’$time’];
Filter  
{{expression | filterName:paramter1:…paramterN}}
内置:
currency、date、number/uppercase
自定义:
 
<html ng-app ="filterModule">
<title>系统filter</title>
<style type="text/css">
.selected{background:lightgreen;}
</style>
 
<body>
<div ng-controller = "priceController">
<!--JSON-->
{{ {foo: "bar", baz: 23} | json }} 
 
<!--货币-->
<p>{{250 | currency}}</p>
<p>{{ 250 | currency:"RMB ¥ " }}  </p>
 
<!--日期-->
<p>{{ 1427109979466 | date }} </p>
<p>{{ 1427109979466 | date:"MM/dd/yyyy @ h:mma" }} </p>
<p>{{ 1427109979466 | date:"yyyy-MM-dd hh:mm:ss" }} </p>
 
 
<!--数字-->
<p>{{ 1.234567 | number:1 }} </p>
<p>{{ 1234567 | number }}</p>    
 
<!--filter查找-->
{{ [{"age": 20,"id": 10,"name": "iphone"},  
{"age": 12,"id": 11,"name": "sunm xing"},  
{"age": 44,"id": 12,"name": "test abc"}  
] | filter:‘s‘}} 
 
<!--limitTo截取-->
<p>{{ "This is angularjs" | limitTo:7 }} </p>
<p>{{ "This is angularjs" | limitTo:-2 }}</p>
<p>{{[1,2,3] | limitTo:1 }}</p>
 
<!--orderBy对像排序-->
 
{{ [{"age": 20,"id": 10,"name": "iphone"},  
{"age": 12,"id": 11,"name": "sunm xing"},  
{"age": 44,"id": 12,"name": "test abc"}  
] | orderBy:‘id‘:true }}   //根据id降序排  
  
{{ [{"age": 20,"id": 10,"name": "iphone"},  
{"age": 12,"id": 11,"name": "sunm xing"},  
{"age": 44,"id": 12,"name": "test abc"}  
] | orderBy:‘id‘ }}           //根据id升序排  
</div>
 
 
 
<script type="text/javascript" src="../script/angular.min.js"></script>
<script type="text/javascript">
angular.module(‘filterModule‘,[])
  .controller(‘priceController‘, function($scope) {
 
  });
 
</script>
</body>
</html>
 
<html>
<head>
<title>自定义filter</title>
<script type="text/javascript" src="../script/angular.min.js"></script>
</head>
<body ng-app="filterModule" ng-controller="filterController">
<h1>{{pageHeading | titleCase }}</h1>
</body>
 
 
<script type="text/javascript">
angular.module(‘filterModule‘,[])
.filter(‘titleCase‘,function(){
return function(text){
var words = text.split(‘ ‘);
for(var i=0,len=words.length;i<len;i++){
words[i] = words[i].charAt(0).toUpperCase()+words[i].slice(1);
}
return words.join(‘ ‘);
}
})
.controller("filterController",function($scope){
$scope.pageHeading = "this is filter";
})
 
</script>
 
</html>
 
factory、service 、provider
service(name, constructor)
factory(name,$getFunction())
provider(name,Objector constructor())
技术分享
 1  
 2 <html>
 3 <head>
 4 <title>demo</title>
 5 <script type="text/javascript" src="../script/angular.min.js"></script>
 6 </head>
 7 <body ng-app="myApp" ng-controller="myController">
 8 <p>facetorytest:{{factorytest}}</p>
 9 <p>servicetest:{{servicetest}}</p>
10 <p>providertest:{{providertest}}</p>
11  
12 </body>
13 <script type="text/javascript">
14 var myApp = angular.module("myApp",[]);
15 myApp.factory("factorytest",function(){
16 var test = {};
17 test.name = "factorytest";
18 return test;
19 })
20 myApp.service("servicetest",function(){
21 this.name = "servicetest";
22 })
23 myApp.provider("providertest",function(){
24 this.$get = function(){return  "providertest";}
25  
26 })
27 myApp.controller("myController",function($scope,factorytest,servicetest,providertest){
28 $scope.factorytest = factorytest.name;
29 $scope.servicetest = servicetest.name;
30 $scope.providertest = providertest;
31 })
32 </script>
33 </html>
34  
35  
View Code

 

 
 
 
 
 
 
 directive
myModule.directive(‘directive’,functionfactory(injectables){
    var directiveDefinitionObject ={
   }
  return directiveDefinitionObject ;
})
compile和link 
Angular初始化:
加载脚本
编译阶段:(遍历dom,根据指令(template、replace)转换dom结构),存在compile函数则调用 ,scope在链接阶段才会被绑定到元素上,因此compile阶段操作scope会报错;
链接阶段: 为了让视图成为动态,对每条指令运行一个link函数;
对于同一个指令的多个实例,compile只会执行一次;而link对于指令的每个实例都会执行一次;
 
伪代码:
var myModule = angular.module(...);
myModule.directive(‘namespacesDirectiveName‘,function factory(injectables){
var directiveDefinitionObject = {
restrict:string,/* E 元素  A 属性 C 样式类 M 注释 */
priority:number,
tamplate:string,
tamplateUrl:string,
replace:bool,
transclude:bool, /*把当前指令中的子节点移动到模板的内部*/
scope:bool or object,
controller:function controllerConstructor($scope,$element,$attrs,$transclude){
...
},
require:string,
link:function postLink(scope,iElement,iAttrs){
...
},/*实例元素 Instance*/
compile:function compile(tElement,tAttrs,transclude){
return {
pre:function preLink(scope,iElement,iAttrs,controller){...},
post:function preLink(scope,iElement,iAttrs,controller){...}
}
}/*模板元素 tamplate*/
}
return directiveDefinitionObject;
})
 
demo1:
 
技术分享
 1 <body ng-app="app">
 2 <hello></hello>
 3 </body>
 4 <script type="text/javascript">
 5 var appModule = angular.module(app, []);
 6 appModule.directive(hello, function() {
 7 return {
 8 restrict: E,
 9 template: <div >Hi there</div>,
10 replace: false
11 };
12 });
View Code

 

 
/*
restrict:
E 元素 
A 属性
C 样式类
M 注释
*/
</script>
 
demo2:
技术分享
 1 <body ng-app="app">
 2  <hello>
 3 <br/>
 4 <span>原始的内容,</span><br/>
 5 <span>还会在这里。</span>
 6 </hello>
 7 <hello>
 8 </hello>
 9 </body>
10 <script type="text/javascript">
11 var appModule = angular.module(app, []);
12     appModule.directive(hello, function() {
13     return {
14         restrict: E,
15         template: <div>替换内容 <span ng-transclude></span></div>,
16         transclude: true
17     };
18 });
19 </script>
View Code

 

 
 
demo3:
技术分享
 1  
 2 <body ng-app="app">
 3  <hello>
 4 <span>原始的内容,</span>
 5 </hello>
 6 <hello>
 7 </hello>
 8 </body>
 9 <script type="text/javascript">
10 var appModule = angular.module(app, []);
11 /*
12 appModule.run(function($templateCache){
13 $templateCache.put(‘templateId.html‘,‘<div>templateUrl</div>‘)
14 })*/
15 appModule.directive(hello, function() {
16     return {
17         restrict: E,
18         templateUrl: templateId.html,
19         transclude: true
20     };
21 });
22 </script>
View Code

 

demo4:
技术分享
 1 <html>
 2 <head>
 3 <title></title>
 4 <script type="text/javascript" src="../script/angular.min.js"></script>
 5 <style type="text/css">
 6 .expander {
 7 border: 1px solid red;
 8 width: 250px;
 9 }
10  
11 .expander>.title {
12  
13 color: white;
14 padding: 1em 3em;
15 cursor: pointer;
16 }
17  
18 .expander>.body {
19 padding: 1em 3em;
20 }
21 .close{display:none;}
22 </style>
23 </head>
24 <body ng-app="app" ng-controller="SomeController">
25 <expander class="expander" aa-a="title" expander-text="text">
26 {{text}}
27 </expander>  
28  
29 <!--<input type="text" ng-model="title"/>-->
30  
31 </body>
32 <script type="text/javascript">
33 var appModule = angular.module(app, []);
34  
35 appModule.directive(expander, function() {
36 return {
37 restrict: E,
38 replace: true,
39 transclude:true,
40 scope:{Title:=aaA},/*创建scope的局部属性,与父scope中的expander-title绑定*/
41 template:<div>+
42 <div class="title" ng-click="toggle()">{{Title}}</div>+
43 <div class="body" ng-transclude></div>+
44 </div>,
45 link:function(scope,element,attrs){
46 console.log(element)
47 var titleElement = angular.element(element.children().eq(0));
48 var bodyElement = angular.element(element.children().eq(1));
49 titleElement.bind(click,toggle);
50 function toggle(){
51 bodyElement.toggleClass(close);
52 }
53 }
54 };
55 });
56 appModule.controller("SomeController",function($scope){
57 $scope.title = "Click me to expand";
58 $scope.text = Toggle Information;
59 })
60  
61  
62  
63 </script>
64 </html>
View Code

 

templateId.html
<div>xxxxxxxxxxxx</div>
 
route
通过$routeRrovider服务上的函数来创建路由,把需要创建的路由当成配置块传给模块即可。  
 
技术分享
1 var someModule = angular.module(‘someModule‘,[..moduleDependencies..])
2 someModule.config(function($routerProvider){
3 $routerProvider.
4 when(‘url‘,{controller,templateUrl:‘/path/to/template‘}).
5 when(...other mappings for you app...).
6 otherwise(...what to do if nothing else matches...)
7 })
8  
View Code

 

index.html
 
技术分享
 1 <html ng-app=‘AMail‘>
 2  
 3 <head>
 4 <script type="text/javascript" src="http://angular.100bt.com/script/angular.min.js"></script>
 5 <script type="text/javascript" src="http://angular.100bt.com/angular-route.js"></script>
 6 <script type="text/javascript" src="script/controllers.js"></script>
 7 </head>
 8  
 9 <body>
10 <h1>A-Mail</h1>
11 <div ng-view></div>
12  
13  
14 </body>
15  
16 </html>
View Code

 

 
list.html
 
技术分享
 1 <table>
 2 <tr>
 3 <td><strong>Sender</strong></td>
 4 <td><strong>Subject</strong></td>
 5 <td><strong>Date</strong></td>
 6 </tr>
 7 <tr ng-repeat=‘message in messages‘>
 8 <td>{{message.sender}}</td>
 9 <td><a href="#/view/{{message.id}}">{{message.subject}}</a></td>
10 <td>{{message.date}}</td>
11 </tr>
12 </table>
View Code

 

 
 
detail.html
 
技术分享
1 <div><strong>Subject:</strong>{{message.subject}}</div>
2 <div><strong>Sender:</strong>{{message.sender}}</div>
3 <div><strong>Date:</strong>{{message.date}}</div>
4 <div>
5 <strong>To:</strong>
6 <span ng-repeat=‘recipient in message.recipients‘>{{recipient}}</span>
7 </div>
8 <div>{{message.message}}</div>
9 <a href="#/">Back to message list</a>
View Code

 

 
controllers.js
 
技术分享
 1 var aMailServices = angular.module(‘AMail‘,["ngRoute"])
 2 function emailRouteConfig($routeProvider){
 3 $routeProvider.when(‘/‘,{
 4 controller:ListController,
 5 templateUrl:‘list.html‘
 6 }).when(‘/view/:id‘,{
 7 controller:DetailController,
 8 templateUrl:‘detail.html‘
 9 }).otherwise({
10 redirectTo:‘/‘
11 });
12 }
13  
14 aMailServices.config([‘$routeProvider‘,emailRouteConfig]);
15  
16 messages  = [
17 {
18 id:0,
19 sender:‘0@qq.com‘,
20 subject:‘0mail‘,
21 date:"0:00:00",
22 recipients:[‘00.qq.com‘],
23 message:‘this is 0 mail‘
24 },{
25 id:1,
26 sender:‘1@qq.com‘,
27 subject:‘1mail‘,
28 date:"1:00:00",
29 recipients:[‘11.qq.com‘],
30 message:‘this is 1 mail‘
31 },{
32 id:2,
33 sender:‘2@qq.com‘,
34 subject:‘2mail‘,
35 date:"2:00:00",
36 recipients:[‘22.qq.com‘],
37 message:‘this is 2 mail‘
38 }
39 ]
40  
41 function ListController($scope,$routeParams){
42 $scope.messages = messages;
43 }
44  
45 function DetailController($scope,$routeParams){
46 $scope.message = messages[$routeParams.id];
47 }
View Code

 

 
 

angularjs介绍

标签:

原文地址:http://www.cnblogs.com/peace1/p/4448235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!