AngularJS 实例
AngularJS实例入门 Google一下有很多关于AngularJS的文档。
目前版本:v1.2.16
(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 和 {{}} 的区别:
http://stackoverflow.com/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" required ng-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!';
};
}
//-->
</script>
</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'}
];
}
//-->
</script>
</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 = 'http://www.baidu.com';
$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('myProvider.name');
console.log('myConstant = ' + myConstant + ', myConstantObj.name = ' + myConstantObj.name);
myConstantObj.name = 'FUGA';
})
.run(function(myService, myProvider, myConstant, myConstantObj, myValue) {
console.log('run');
myService.method();
console.log(myProvider.name);
console.log('myConstant = ' + myConstant + ', myConstantObj.name = ' + myConstantObj.name+ ', 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}} {{physicist.lastName}}
</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.name}}({{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>的ID
templateUrl: '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', [])
.directive('myHoge', function() {
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', [])
.directive('myHoge', function() {
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>
(30)link可以被执行多次
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>link可以被执行多次</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
(function() {
angular.module('myModule', [])
.directive('myHoge', function() {
return {
restrict: 'E',
link: function($scope, $element, $attr) {
// link每个指令的实例执行一次
console.log('link');
}
};
});
})();
//-->
</script>
</head>
<body>
<ul>
<li ng-repeat="i in [1, 2, 3]">
<my-hoge />
</li>
</ul>
</body>
</html>
(31)同时使用compile和link
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>同时使用compile和link</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');
// compile的返回值就是link函数
return function($scope, $element, $attr) {
console.log('link');
};
}
};
});
})();
//-->
</script>
</head>
<body>
<ul>
<li ng-repeat="i in [1, 2, 3]">
<my-hoge />
</li>
</ul>
</body>
</html>
(32)指令的默认scope
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>指令的默认scope</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
(function() {
angular.module('myModule', [])
.controller('SampleController', function($scope) {
$scope.message = 'sample controller';
})
.directive('myHoge', function() {
return {
restrict: 'E',
link: function($scope) {
// 默认是父元素所对应的scope,可以直接使用或修改数据
console.log('$scope.message = ' + $scope.message);
}
};
});
})();
//-->
</script>
</head>
<body>
<div ng-controller="SampleController">
<my-hoge />
</div>
</body>
</html>
(33)指令自己的scope(继承自父元素)
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>指令自己的scope(继承自父元素)</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
(function() {
var parentScope;
angular.module('myModule', [])
.controller('SampleController', function($scope) {
$scope.message = 'sample controller';
parentScope = $scope;
})
.directive('myHoge', function() {
return {
restrict: 'E',
scope: true,// 设置成true,继承父元素的scope但是一个新的scope
link: function($scope) {
// 这里的scope就不是父元素的scope,追加修改scope的数据不会对父元素造成影响
console.log('($scope === parentScope) = ' + ($scope === parentScope));// false
console.log('$scope.message = ' + $scope.message);
}
};
});
})();
//-->
</script>
</head>
<body>
<div ng-controller="SampleController">
<my-hoge />
</div>
</body>
</html>
(34)指令自己的scope(和父元素无关)
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>指令自己的scope(和父元素无关)</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
(function() {
var parentScope;
angular.module('myModule', [])
.controller('SampleController', function($scope) {
$scope.message = 'hoge fuga piyo';
$scope.func = function() {
return 'HOGE FUGA PIYO';
};
parentScope = $scope;
})
.directive('myHoge', function() {
return {
restrict: 'A',
scope: {
msg: '=myMessage', // =<属性名> 单纯的字符串
str: '@myString', // @<属性名> 字符串中可以使用{{}}
func: '&myFunc' // &<属性名> 函数
}, // scope是一个对象的时候,跟父元素的scope将无关
link: function($scope) {
// 这里的scope是一个新的对象
console.log('($scope === parentScope) = ' + ($scope === parentScope));// false
console.log('$scope.message = ' + $scope.message); // undefined
console.log('$scope.msg = ' + $scope.msg);
console.log('$scope.str = ' + $scope.str);
console.log('$scope.func() = ' + $scope.func());
}
};
});
})();
//-->
</script>
</head>
<body>
<div ng-controller="SampleController">
<div my-hoge my-message="message" my-string="message, {{message}}" my-func="func()"></div>
</div>
</body>
</html>
(35)指令自己的scope(和父元素无关)-省略属性名
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>指令自己的scope(和父元素无关)-省略属性名</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
(function() {
var parentScope;
angular.module('myModule', [])
.controller('SampleController', function($scope) {
$scope.message = 'hoge fuga piyo';
$scope.func = function() {
return 'HOGE FUGA PIYO';
};
parentScope = $scope;
})
.directive('myHoge', function() {
return {
restrict: 'A',
scope: {
myMessage: '=',// scope对象的属性名和指令的属性名相同的时候,可以省略
myString: '@',
myFunc: '&'
},
link: function($scope) {
console.log('($scope === parentScope) = ' + ($scope === parentScope));// false
console.log('$scope.message = ' + $scope.message); // undefined
console.log('$scope.msg = ' + $scope.myMessage);
console.log('$scope.str = ' + $scope.myString);
console.log('$scope.func() = ' + $scope.myFunc());
}
};
});
})();
//-->
</script>
</head>
<body>
<div ng-controller="SampleController">
<div my-hoge my-message="message" my-string="message, {{message}}" my-func="func()"></div>
</div>
</body>
</html>
(36)标签内多个指令间的调用
<!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('myParent', function() {
return {
// 指令间调用的话,被调用侧使用controller
controller: function() {
this.method = function() {
console.log('Parent Controller');
};
}
};
})
.directive('myChild', function() {
return {
// 调用侧require调用的指令名
// <指令名> 该指令不存在的时候抛异常
// <@指令名> 该指令不存在的时候忽略
// <^指令名> 查找父元素的该指令,比如<my-parent> <my-child /> </my-parent>
require: 'myParent',
// link的第4个参数指定被调用侧的controller
link: function($scope, $element, $attr, cntroller) {
cntroller.method();
}
};
});
})();
//-->
</script>
</head>
<body>
<div my-parent my-child> </div>
</body>
</html>
(37)操作URL
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="UTF-8">
<title>操作URL</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
function SampleController($location, $filter) {
var str = 'absUrl() = ' + $location.absUrl() + '\r\n'
+ 'url() = ' + $location.url() + '\r\n'
+ 'protocol() = ' + $location.protocol() + '\r\n'
+ 'host() = ' + $location.host() + '\r\n'
+ 'port() = ' + $location.port() + '\r\n'
+ 'path() = ' + $location.path() + '\r\n'
+ 'search() = ' + $filter('json')($location.search()) + '\r\n'
+ 'hash() = ' + $location.hash() + '\r\n';
console.log(str);
};
//-->
</script>
</head>
<body ng-controller="SampleController">
</body>
</html>
(38)setTimeOut处理
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta charset="UTF-8">
<title>setTimeOut处理</title>
<script src="angular.min.js"></script>
<script language="JavaScript">
<!--
(function() {
angular.module('myModule', [])
.run(function($timeout) {
var promise = $timeout(function() {
console.log('hoge');
}, 1000);
console.log('fuga');
promise.then(function() {
console.log('piyo');
});
});
})();
//-->
</script>
</head>
<body>
</body>
</html>
(39)日志处理
<!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', [])
.config(function($logProvider) {
$logProvider.debugEnabled(false);
})
.run(function($log) {
$log.log('log');
$log.debug('debug');
$log.info('info');
$log.warn('warn');
$log.error('error');
});
})();
//-->
</script>
</head>
<body>
</body>
</html>
(40)捕获异常
<!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', [])
.config(function($provide) {
$provide.decorator('$exceptionHandler', function($delegate) {
// 发生异常时的处理
return function(exception, cause) {
console.log('intercept');
$delegate(exception, cause);
};
});
})
.controller('SampleController', function($scope) {
notExists.method();
});
})();
//-->
</script>
</head>
<body ng-controller="SampleController">
</body>
</html>

参考: http://www.angularjshub.com/ https://www.ng-book.com/ http://qiita.com/opengl-8080/items/2fe0a20c314b1c824cc5

浙公网安备 33010602011771号