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>。