angularjs入门范例
- 格式:doc
- 大小:351.82 KB
- 文档页数:54
AngularJS学习(一)——概览1. 文章简述这篇主要通过几个小例子把angular的常用组件简单介绍一下2. data binding下面是一个简单通过quantity和costs计算Total的示例<div ng-appng-init="qty=1;cost=2"><b>Invoice:</b><div>Quantity: <input type="number"min="0"ng-model="qty"> </div><div>Costs: <input type="number"min="0"ng-model="cost"></div><div><b>Total:</b> {{qty * cost | currency}}</div></div>输出结果下面描述一下这段代码是如何运行的,这段代码看起来像一个带着一些新的标记的普通html 文件,在angular中,这样的文件叫template,当angular运行时,它会从这个template中去解析处理这些新的标记,并且加载、转换和呈现以dom的形式。
第一种标记在angular中被称为directives,他们为一些属性或者元素增加特殊的功能,比如上面的ng-app属性,angular识别到它会自动初始化为angular应用程序。
angular也为input 元素增加一些扩展的功能,比如接下来的ng-model,他可以将input的值存储到一个变量中,也可以把变量的值赋予到input中,这这绑定是live的绑定,一个变化另一个随之变化,称之为双向绑定。
angular学习笔记(⼀)-⼊门案例⼊门实例:⼀个购物车产品清单,可以⾃⾏改变数量,总价⾃动计算的⼩例⼦:代码如下:<!DOCTYPE html><html ng-app><head><title>1.1实例:购物车</title><meta charset="utf-8"><script src="../angular.js"></script><script src="script.js"></script><style type="text/css">.red {color:#cc0000}* {font-family:'MICROSOFT YAHEI'}TD {font-size:12px; color:#999;}</style></head><body ><div ng-controller="CarController"><h1>your shopping cart</h1><table><tr ng-repeat="item in items"><td>{{item.title}}</td><td><input ng-model="item.quantity"/></td><td>{{item.price|currency}}</td><td class="red">{{item.price*item.quantity|currency}}</td><td><button ng-click="remove($index)">remove</button></td></tr></table></div></body></html>script.js代码:function CarController ($scope) {$scope.items = [{"title":"兔⼦","quantity":1,"price":"100"},{"title":"喵","quantity":1,"price":"200"},{"title":"狗只","quantity":1,"price":"400"},{"title":"仓⿏","quantity":1,"price":"300"}];$scope.remove = function(index){$scope.items.splice(index,1)}}下⾯对以上代码进⾏说明:1.ng-app:<html ng-app>:ng-app属性,⽤来告诉页⾯哪⼀部分需要使⽤angular管理.通常情况下都这样管理.(但是我在师傅的⽹站上看到不是这样的,是加在其它div上⾯的,⽽且是有值的.这个学到后⾯再说)2. ng-controller:<div ng-controller="CarController">使⽤⼀个控制器来控制页⾯中的某个区域,这⾥就是管理这个<div>到</div>⾥的所有内容这⾥使⽤的控制器就是script.js⾥定义的CarController函数3. ng-repeat:<tr ng-repeat="item in items">循环当前的标签(包括⾥⾯的内容和⾃⼰),循环中的当前变量就是item,item在当前作⽤域的items变量⾥进⾏循环即CarController⾥定义的$scope.items数组4. {{ }}:<td>{{item.title}}</td>使⽤{{}}来动态的绑定视图⾥显⽰的数据.{{}}⾥就是当前作⽤域⾥的变量5. ng-model:ng-model="item.quantity"ng-model⽤在输⼊框⾥,使输⼊的内容和它等于的变量数据进⾏绑定,也就是说,输⼊的值变化,变量就变化,变量变化,视图上对应显⽰的数据也变化6. currency:<td>{{item.price|currency}}</td><td class="red">{{item.price*item.quantity|currency}}</td>angular带有过滤器特性,可以⽤来做⽂本格式的转换,其中,currency货币过滤器,可以实现美元格式化7. ng-click:<button ng-click="remove($index)">remove</button>为元素绑定click事件的回调,点击后就调⽤作⽤域下的remove⽅法,也就是在CarController中添加的remove⽅法8. $index:remove($index)$index是在ng-repeat过程中的循环的索引值,从0开始9. 控制器:function CarController ($scope) {...}控制器负责管理相关的区域的逻辑.函数的形参$scope就是当前区域的作⽤域,区域中的变量,⽅法,都从它的作⽤域中寻找.⽐如这⾥的$scope.items和$scope.remove10. 另外,ng-repeat所创建的列表是和数据的更新事实绑定的,所以当使⽤remove⽅法删除数据中的某⼀组数据,那么,视图中相应的ui也会被删除.相关代码托管:https:///OOP-Code-Bunny/angular。
AngularJS-⼊门⼩DemoAngularJS四⼤特效MVC模式、模块化设计、⾃动化双向数据绑定、依赖注⼊如果了解了后端开发知识,想必对这些词汇不会陌⽣,AngularJS融合了后端开发的⼀些思想,虽然⾝为前端框架,但与jQuery框架却是完全不相同的东西。
AngularJS分为⼏个模块,需要使⽤哪个模块的功能,就直接引⼊对应的模块,这种模块化设计具备⾼内聚、低耦合的特点。
官⽅提供的模块有:ng、ngRoute、ngAnimate⽤户也可以⾃定义模块:angular.module('模块名', [])这⾥的ng是引擎engine的缩写,类似于Nginx的Ngin也是engine的缩写(谐⾳?)Demo1 - 表达式在当前⽬录下新建⼀个demo-1.html⽂件,并将angular.min.js⽂件放置在同⼀⽬录下。
<html><head><title>AngularJS⼊门⼩Demo-1 表达式</title><script src="angular.min.js"></script></head><body ng-app>{{100+100}}</body></html>通过在html中引⼊angular.min.js,并在body标签中加⼊ng-app指令,则会对{{}}⾥的表达式进⾏计算。
双击打开这个html⽂件,会发现页⾯显⽰的是200,如果不加载ng-app指令,页⾯显⽰的则是{{100+100}}。
Demo2 - 双向绑定<html><head><title>AngularJS⼊门⼩Demo-2 双向绑定</title><script src="angular.min.js"></script></head><body ng-app>请输⼊姓名:<input ng-model="name"><br>请输⼊姓名:<input ng-model="name"><br>{{name}}</body></html>通过ng-model来绑定变量,双击上边的页⾯⽂件,在任意⼀个输⼊框中输⼊字符,都会影响到绑定同⼀变量的标签元素。
AngularJS权威教程Hello World!开始学习AngularJS的一个好方法是创建经典应用程序“Hello World!”:使用您喜爱的文本编辑器,创建一个HTML文件,例如:helloworld.html。
将下面的源代码复制到您的HTML文件。
在web浏览器中打开这个HTML文件。
源代码<!doctype html><html ng-app><head><script src=" :///angular-1.0.1.min.js"></script></head><body>Hello {{'World'}}!</body></html>请在您的浏览器中运行以上代码查看效果。
现在让我们仔细看看代码,看看到底怎么回事。
当加载该页时,标记ng-app告诉AngularJS 处理整个HTML页并引导应用:<html ng-app>这行载入AngularJS脚本:<script src=" :///angular-1.0.1.min.js"></script>(想了解AngularJS处理整个HTML页的细节,请看Bootstrap。
)最后,标签中的正文是应用的模板,在UI中显示我们的问候语:Hello {{'World'}}!注意,使用双大括号标记{{}}的内容是问候语中绑定的表达式,这个表达式是一个简单的字符串‘World’。
下面,让我们看一个更有趣的例子:使用AngularJS对我们的问候语文本绑定一个动态表达式。
Hello AngularJS World!本示例演示AngularJS的双向数据绑定(bi-directional data binding):编辑前面创建的helloworld.html文档。
AngularJS⼊门(⽤ng-repeat指令实现循环输出循环输出列表很多项⽬在web服务端做,前端做好模版后后端写jsp代码,双⽅需要紧密合作,分清责任。
有些项⽬由后端提供restful⽅法,前端⽤ajax调⽤⾃⼰循环,这种⼀般是⼤把的jquery拼字符串,太不直观,有⼈搞出了js模板,也没好到哪⾥去。
⽤AngularJS就爽多了,语法和JSP类似:<!doctype html><html ng-app><head><meta charset="utf-8"><title>ng-repeat directive</title></head><body><table ng-controller="CartController"><caption>我的购物车</caption><tr><th>序号</th><th>商品</th><th>单价</th><th>数量</th><th>⾦额</th><th>操作</th></tr><tr ng-repeat="item in items"><td>{{$index + 1}}</td><td>{{}}</td><td>{{item.price | currency}}</td><td><input ng-model="item.quantity"></td><td>{{item.quantity * item.price | currency}}</td><td><button ng-click="remove($index)">Remove</button></td></tr></table><script src="../lib/angularjs/1.2.26/angular.min.js"></script><script>function CartController($scope) {$scope.items = [{name: "雷柏(Rapoo) V500 机械游戏键盘机械黄轴", quantity: 1, price: 199.00},{name: "雷柏(Rapoo) V20 光学游戏⿏标⿊⾊烈焰版", quantity: 1, price: 139.00},{name: "AngularJS权威教程", quantity: 2, price: 84.20}];$scope.remove = function (index) {$scope.items.splice(index, 1);}}</script></body></html>ng-repeat指令⽣命在需要循环内容的元素上,items和控制器上的变量名对应,item是为数组中单个对象起的别名。
为什么这样写像所有程序的开始一样,使用AngularJS也从Hello world 开始书写Html 结构<html><head><title>学习Angularjs1.x</title></head><body ng-app="MyApplication"><script src="/libs/angular.js/1.5.0-beta.0/angular.min.j s"></script><script type="text/javascript">// 这里是JS 代码</script></body></html>∙1∙2∙3∙4∙5∙6∙7∙8∙9∙10∙11∙1∙2∙3∙4∙5∙6∙7∙8∙9∙10∙11输出一个Hello world<html ng-app="MyApplication"><head><title>学习Angularjs1.x</title></head><body ng-controller="HelloWorld"><div ng-bind="text"></div><script src="/libs/angular.js/1.5.0-beta.0/angular.min.j s"></script><script type="text/javascript">// 这里是JS 代码angular.module('MyApplication', []).controller('HelloWorld', ['$scope', function($scope){$scope.text = "Hello world";}]);</script></body></html>∙1∙2∙3∙4∙5∙6∙7∙8∙9∙10∙11∙12∙13∙14∙15∙16∙1∙2∙3∙4∙5∙6∙7∙8∙9∙10∙11∙12∙13∙14∙15∙16复制以上DEMO 到自己的HTML 文件中,运行即可。
AngularJS简介AngularJS(简称ng,官网api地址:/api)是由Google创建的一种JS框架,是一个新出现的强大客户端技术,提供给大家的一种开发强大应用的方式。
这种方式利用并且扩展HTML,CSS和javascript,并且弥补了它们的一些非常明显的不足。
AngularJS是为了克服HTML在构建应用上的不足而设计的。
HTML是一门很好的为静态文本展示设计的声明式语言,但要构建WEB应用的话它就显得乏力了。
AngularJS尝试去补足HTML本身在构建应用方面的缺陷。
AngularJS通过使用我们称为标识符(指令)(directives)的结构,让浏览器能够识别新的语法。
例如:使用双大括号{{}}语法进行数据绑定;使用DOM控制结构来实现迭代或者隐藏DOM片段;支持表单和表单的验证;能将逻辑代码关联到相关的DOM元素上;能将HTML分组成可重用的组件。
特性MVC针对客户端应用开发AngularJS吸收了传统的MVC基本原则。
MVC或者Model-View-Controll设计模式针对不同的人可能意味不同的东西。
AngularJS并不执行传统意义上的MVC,更接近于 MVVM(Moodel-View-ViewModel)。
Model: 是应用中的简单数据。
一般是简单的javascript对象。
ViewModel:是一个用来提供特别数据和方法从而维护指定view的对象。
viewmodel是$scope的对象,只存在于AnguarJS的应用中。
$scope只是一个简单的js对象,这个对象使用简单的API来侦测和广播状态变化。
Controller:负责设置初始状态和参数化$scope方法用以控制行为。
需要指出的是controller 并不保存状态也不和远程服务互动。
View:是AngularJS解析、渲染和绑定数据后产生的HTML。
双向数据绑定数据绑定可能是AngularJS最酷最实用的特性。
AngularJS入门一、总括本文用于解释Angular初始化的过程,以及如何在你有需要的时候对Angular进行手工初始化。
二、Angular <script> 标签本例用于展示如何通过推荐的路径整合Angular,实现自动初始化。
<!doctype html><html xmlns:ng="" ng-app><body>...<script src="angular.js"></body></html>∙将sciprt标签放置于页面底部。
这样做能避免因为加载angular.js而阻挡HTML的加载,从而降低应用的加载时间。
我们可以在中获取到最新版本的angularJs。
出于安全考虑,切勿在产品中直接引用这个地址来加载脚本。
但如果仅仅是研究学习使用的话,直接连接也无妨。
∙o选择:angular-[version].js 是方便阅读的一个版本,适合日常开发、调试使用。
o选择:angular-[version].min.js 是压缩、混淆后的版本,适合最终产品使用。
∙放置”ng-app”到应用的根节点中,如果你想让angular自动启动你的应用,通常可以放置于<html>标签中。
<html ng-app>∙如果我们需要使用老派风格的directive语法”ng:”,那么我们需要加入一个xml-namespace 到html标签中以“取悦”IE。
(这个是一个历史原因,我们也不推荐使用ng:)<html xmlns:ng="">三、自动初始化Angular会在DOMContentLoaded事件中自动初始化,Angular会找出由你通过ng-app这个directive指定的应用根节点。
如果找到,Angular会做以下事情:∙加载与module相关的directive。
AngularJS实例入门Google一下有很多关于AngularJS的文档。
(1)基本构造<!DOCTYPE html><!-- ng-app指令标记了AngularJS脚本的作用域(可在局部使用比如div) --> <html ng-app><head><meta charset="UTF-8"><title>基本构造</title><script src="angular.min.js"></script><script language="JavaScript"><!--// 定义HTML中ng-controller指定的同名函数function SampleController($scope) {// 借助于参数$scope为页面输出数据$scope.message = 'Hello World!';}//--></script></head><body><!-- ng-controller指令指定控制器 --><h1 ng-controller="SampleController"><!-- 用{{}}输出容 --><p>{{message}}<p>{{5 * 3}}</h1></body></html>(2)输出数据<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>输出数据</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.simple = '使用简化写法输出容';$scope.directive = '使用指令输出容';}//--></script></head><body><div ng-controller="SampleController"><p>{{simple}}</p><p ng-bind="directive"></p><!--ng-bind 和 {{}} 的区别:stackoverflow./questions/16125872/why-ng-bind-is-better-than-in-angular --></div></body></html>(3)显示/隐藏<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>显示/隐藏</title><script src="angular.min.js"></script></head><body><div><!-- ng-show的值为true时显示,false时隐藏 --> <div ng-show="true"> Visible </div><div ng-show="false"> Invisible </div></div></body></html>(4)表单校验<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>表单校验</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {}//--></script></head><body><form novalidate name="myForm" ng-controller="SampleController"><input type="text" name="id" ng-model="user.id" required ng-maxlength="6"/> <span ng-show="myForm.id.$error.required">Required</span><span ng-show="myForm.id.$error.maxlength">Too long!</span><br/><input type="text" name="pass" ng-model="user.pass" requiredng-minlength="5"/><span ng-show="myForm.pass.$error.required">Required</span><span ng-show="myForm.pass.$error.minlength">Too short!</span></form></body></html>(5)表单<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>表单</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.text = 'TextBox';$scope.checkbox = true;$scope.radio = 'FUGA';$scope.select = 'foo';}//--></script></head><body><form ng-controller="SampleController"><!-- ng-model指令用来捆绑$scope和输入项 --><input type="text" ng-model="text" /><input type="checkbox" ng-model="checkbox" /><input type="radio" name="hoge" value="HOGE" ng-model="radio" />HOGE<input type="radio" name="hoge" value="FUGA" ng-model="radio" />FUGA <select ng-model="select"><option value="foo">Foo</option><option value="bar">Bar</option></select><!-- 用{{}}实时输出容 --><hr>你输入了: {{text}}</form></body></html>(6)事件监听<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>事件监听</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.click = function() {$scope.message = 'click button!';};}//--></head><body><div ng-controller="SampleController"><button ng-click="click()">Button</button> <p>{{message}}</p></div></body></html>(7)循环输出<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>循环输出</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.items = [{key: 'hoge', value: 'HOGE'},{key: 'fuga', value: 'FUGA'},{key: 'piyo', value: 'PIYO'}];}//--></head><body><ul ng-controller="SampleController"><!-- ng-repeat指令所在的标签会被循环输出 --> <li ng-repeat="item in items">{{item.key}} : {{item.value}}</li></ul></body></html>(8)循环输出(顺位)<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>循环输出(顺位)</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.items = [{key: 'hoge', value: 'HOGE'},{key: 'fuga', value: 'FUGA'},{key: 'piyo', value: 'PIYO'}];}</script></head><body><ul ng-controller="SampleController"><!-- $index标示现在输出的顺位(以0开始) --> <li ng-repeat="item in items">{{$index + 1}} {{item.key}} : {{item.value}} </li></ul></body></html>(9)循环输出(操作item)<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>循环输出(操作item)</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.items = [{key: 'hoge', value: 'HOGE', score: 78.5}, {key: 'fuga', value: 'FUGA', score: 88.5}, {key: 'piyo', value: 'PIYO', score: 68.5}}function ItemController($scope) {$scope.increment = function() {$scope.item.score++;}}//--></script></head><body><ul ng-controller="SampleController"><li ng-repeat="item in items" ng-controller="ItemController"> {{$index + 1}} {{item.key}} : {{item.value}} : {{item.score}} <button ng-click="increment()">+1</button></li></ul></body></html>(10)设置CSS类<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>设置CSS类</title><script src="angular.min.js"></script><style>.red { color: red; }.blue { color: blue; }.solid-border { border: 1px solid black; }.dotted-border { border: 1px dotted black; }li { margin-top: 10px; }</style><script language="JavaScript"><!--function SampleController($scope) {$scope.hoge = 'red solid-border';$scope.isRed = true;$scope.isDotted = true;}//--></script></head><body ng-controller="SampleController"><ul><!-- ng-class指令通过Angular表达式设置CSS类字符串的时候,空格隔开多个class可以直接使用数组表示多个class对象的时候,通过{class名:是否显示}来设置--><li ng-class="hoge">hoge</li><li ng-class="['blue', 'solid-border']">fuga</li><li ng-class="{'red': isRed, 'dotted-border': isDotted}">piyo</li> </ul></body></html>(11)给src/href绑数据<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>给src/href绑数据</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.url = '.baidu.';$scope.imageFileName = 'bdlogo.gif';}//--></script></head><body ng-controller="SampleController"><!-- src/href绑数据时需要使用ng-src/ng-href --> <img ng-src="./{{imageFileName}}" /><a ng-href="{{url}}">link</a></body></html>(12)修改Model同时更新view显示<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>修改Model同时更新view显示</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {// 初始显示$scope.message = 'hoge';// 点击后显示$scope.change = function() {// 通过$scope显示的值可以直接修改后自动刷新显示 $scope.message = 'change!!';}}//--></script></head><body ng-controller="SampleController"><h1>{{message}}</h1><button ng-click="change()">change!!</button></body></html>(13)通过$watch监视数据的变化<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>通过$watch监视数据的变化</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.hoge = 0;$scope.fuga = 0;$scope.sum = 0;// 同时监视多个值的变化// 第一个参数(watchFn):返回监视的值,可以是Angular表达式也可以是函数 // 第二个参数(watchAction):值变化时执行的Angular表达式也可以是函数 $scope.$watch('hoge + fuga', 'sum = hoge + fuga');}//--></script></head><body ng-controller="SampleController">hoge : <input type="number" ng-model="hoge" /><br />fuga : <input type="number" ng-model="fuga" /><br /><p>总计 : {{sum}}</p></body></html>(14)定义Module<!DOCTYPE html><html ng-app="myModule"><!-- ng-app指令设置Module名 --><head><meta charset="UTF-8"><title>定义Module</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {// 创建一个module,如果已经存在该module将会被覆盖// 单纯获取一个module使用angular.module('myModule')var myModule = angular.module('myModule', []);myModule.controller('SampleController', function($scope) { $scope.message = 'module';});})();//--></script></head><body ng-controller="SampleController"><h1>{{message}}</h1></body></html>(15)注入service实例<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>注入service实例</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {var myModule = angular.module('myModule', []);// 为Module登录Service(任意Class)// 第一个参数:service名// 第二个参数:service构造函数myModule.service('sampleService', SampleService);// controller中和登录过的service名相同的参数会被自动注入service实例myModule.controller('SampleController', function($scope, sampleService) {$scope.message = sampleService.method();});function SampleService() {this.method = function() {return 'sample service';};}})();//--></script></head><body ng-controller="SampleController"><h1>{{message}}</h1></body></html>(16)实例化复杂的Service<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>实例化复杂的Service</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {var myModule = angular.module('myModule', []);// Service实例生成很复杂的时候使用factory()myModule.factory('sampleService', function() {return {method: function() {return 'sample service created by factory.'}};});myModule.controller('SampleController', function($scope, sampleService) {$scope.message = sampleService.method();});})();//--></script></head><body ng-controller="SampleController"><h1>{{message}}</h1></body></html>(17)Module的常用方法<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>Module的常用方法</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', []).service('myService', function() {this.method = function() {console.log('myService.method()');};}).provider('myProvider', function() {var _name;this.setName = function(name) {_name = name;};this.$get = function() {return {name: _name};};}).constant('myConstant', 'HOGE').constant('myConstantObj', {name: 'Fuga'}).value('myValue', 'PIYO').config(function(myProviderProvider, myConstant, myConstantObj) {console.log('config');myProviderProvider.setName('');console.log('myConstant = ' + myConstant + ', = ' + ); = 'FUGA';}).run(function(myService, myProvider, myConstant, myConstantObj, myValue) {console.log('run');myService.method();console.log();console.log('myConstant = ' + myConstant + ', = ' + + ', myValue = ' + myValue);});})();//--></script></head><body></body></html>(18)过滤器<!DOCTYPE html><html ng-app><head><meta charset="UTF-8"><title>过滤器</title><script src="angular.min.js"></script><script language="JavaScript"><!--function SampleController($scope) {$scope.money = 1000;$scope.array1 = ["hoge", "fuga", "piyo"]; $scope.array2 = ["hoge","fuga",{a: "hoge"},{a: "fuga"},{b: {c: "hoge"}},{b: {c: "fuga"}},];$scope.physicists = [{firstName: 'Johannes', lastName: 'Kepler'}, {firstName: 'Galileo', lastName: 'Galilei'}, {firstName: 'Thomas', lastName: 'Young'}, {firstName: 'Michael', lastName: 'Faraday'}, {firstName: 'Edward', lastName: 'Morley'}, {firstName: 'Niels', lastName: 'Bohr'}];$scope.isEvenNumber = function(number) {return number % 2 == 0;};$scope.contains = function(actual, expected) { return actual.indexOf(expected) != -1;};$scope.date = new Date();$scope.values = [{name: 'taro', age: 15, height: 165},{name: 'takeshi', age: 12, height: 155},{name: 'taichi', age: 15, height: 160},{name: 'takuya', age: 17, height: 170}];}//--></script></head><body ng-controller="SampleController"><!-- {{value | filter}} --><h1>{{money | currency}}</h1><!-- {{ filter_expression | filter : expression : comparator }} --><pre>{{array1 | filter:"g" | json}}</pre><pre>{{array2 | filter:"h" | json}}</pre><!-- filter中使用对象属性 --><ul><li ng-repeat="physicist in physicists | filter:{firstName:'e', lastName: 'l'}">{{physicist.firstName}} {{stName}}</li></ul><!-- filter中使用函数 --><p>{{[1, 2, 3, 4, 5] | filter:isEvenNumber}}</p><!-- 定义比较器 --><p>{{["a", "A", "ab", "c"] | filter:"a":true}}</p><p>{{["a", "A", "ab", "c"] | filter:"a":false}}</p><p>{{["a", "A", "ab", "c"] | filter:"a":contains}}</p><!-- 设置各种各样的输出形式 --><p>{{1000 | currency:"¥"}}</p><p>{{1000 | number:3}}</p><p>{{"HOGE" | lowercase}}</p><p>{{"fuga" | uppercase}}</p><p>{{date | date:"yyyy/MM/dd HH:mm:ss.sss"}}</p><!-- 表达式中使用属性名的字符串 --><ul><li ng-repeat="value in values | orderBy:['age', 'height']">{{}}({{value.age}})({{value.height}} cm)</li></ul></body></html>(19)自定义过滤器<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>自定义过滤器</title><script src="angular.min.js"></script><script language="JavaScript"><!--var module = angular.module('myModule', []);module.filter('myFilter', function() {return function(value, param1, param2) { return param1 + value + param2;};});//--></script></head><body><h1>{{"hoge" | myFilter:"<":">"}}</h1></body></html>(20)JS代码中使用过滤器<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>JS代码中使用过滤器</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {var myModule = angular.module('myModule', []);myModule.controller('SampleController', function($scope, $filter) { var filter = $filter('json');var str = filter({name: 'Taro', age: 17});$scope.str = str;console.log(str);});})();//--></script></head><body ng-controller="SampleController">{{str}}</body></html>(21)自定义指令<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>自定义指令</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', [])// 定义指令.directive('myHoge', function() {return {template: '<u>message = {{message}}</u>'};}).controller('SampleController', function($scope) { $scope.message = 'hoge';});})();//--></script></head><body ng-controller="SampleController"><h1 my-hoge>some string</h1></body></html>(22)指令名的各种使用方法<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>指令名的各种使用方法</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', []).directive('myHoge', function() {return {template: '<u>message = {{message}}</u>'};}).controller('SampleController', function($scope) { $scope.message = 'hoge';});})();//--></script></head><body ng-controller="SampleController"><!-- 以下用法都正确 --><h1 my-hoge>some string</h1><h1 my:hoge>some string</h1><h1 my_hoge>some string</h1><h1 data-my-hoge>some string</h1><h1 data-my:hoge>some string</h1><h1 data-my_hoge>some string</h1><h1 x-my-hoge>some string</h1><h1 x-my:hoge>some string</h1><h1 x-my_hoge>some string</h1></body></html>(23)指令的形式<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>指令的形式</title><script src="angular.min.js"></script> <script language="JavaScript"><!--(function() {angular.module('myModule', []).directive('myHoge', function() {return {restrict: 'E', // E-元素 A-属性 C-样式 M-注释 template: '<h1>hoge</h1>'};}).directive('myFuga', function() {return {restrict: 'A',template: 'fuga'};}).directive('myPiyo', function() {return {restrict: 'CA',template: 'piyo'};});})();//--></script></head><body><my-hoge></my-hoge><h1 my-fuga></h1><h1 class=my-piyo></h1><h2 my-piyo></h2></body></html>(24)替换指令的DOM元素<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>替换指令的DOM元素</title><script src="angular.min.js"></script> <script language="JavaScript"><!--(function() {angular.module('myModule', []).directive('myHoge', function() { return {restrict: 'E',replace: true,template: '<h1>hoge</h1>'};});})();//--></script></head><body><my-hoge></my-hoge></body></html>(25)嵌入式模板<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>嵌入式模板</title><script src="angular.min.js"></script> <script language="JavaScript"><!--(function() {angular.module('myModule', []).directive('myHoge', function() { return {// <script>的IDtemplateUrl: 'hogeTemplate'};}).controller('SampleController', function($scope) { $scope.message = 'hoge';});})();//--></script></head><body ng-controller="SampleController"><div my-hoge></div></body></html><!-- 嵌入式模板 --><script type="text/ng-template" id="hogeTemplate"><h2>message = {{message}}</h2></script>(26)独立模板文件<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>独立模板文件</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', []).directive('myHoge', function() {return {// 通过XMLHttpRequest调入// !!!不支持file:///协议,需要Web服务器!!! templateUrl: 'sample1-26-tpl.html'};}).controller('SampleController', function($scope) {$scope.message = 'hoge';});})();//--></script></head><body ng-controller="SampleController"><div my-hoge></div></body></html><h2>message = {{message}}</h2>(27)标签元素嵌入模板<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>标签元素嵌入模板</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', [])return {transclude: true,template: '<div>Tag data = <span ng-transclude></span></div>' };}).controller('SampleController', function($scope) {$scope.message = 'hoge';});})();//--></script></head><body ng-controller="SampleController"><h1 my-hoge>hoge</h1></body></html>(28)解析指令前的处理<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>解析指令前的处理</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', [])return {// 显示指令容前的处理// $element:指令所在元素 $attr:指令所在元素的属性 compile: function($element, $attr) {console.log('compile');console.log('$attr.id = ' + $attr.id);$element.append('<li>four</li>');}};});})();//--></script></head><body><ul my-hoge id="list"><li>one</li><li>two</li><li>three</li></ul></body></html>(29)compile只能被执行一次<!DOCTYPE html><html ng-app="myModule"><head><meta charset="UTF-8"><title>compile只能被执行一次</title><script src="angular.min.js"></script><script language="JavaScript"><!--(function() {angular.module('myModule', []).directive('myHoge', function() {return {restrict: 'E',compile: function($element, $attr) {// 跟指令的实例个数无关,即使处于循环之中也只执行一次 console.log('compile');}};});})();//--></script></head><body><ul><li ng-repeat="i in [1, 2, 3]"><my-hoge /></li></ul></body></html>。