## 第八章 指令簡介
調用指令意味著執行指令背后與之相關聯的 JavaScript 代碼,這些代碼是我們用指令定義寫出來的。
### 作用
* 監視數據模型的變化.
* 可以將數據模型的變化通知整個應用,甚至是系統外的組件.
* 可以嵌套,隔離業務功能和數據.
* 給表達式提供運算時所需的執行環境.
### 聲明方式
聲明指令本質上是在HTML中通過元素(E)、屬性(A)、類(C)或注釋(M)來添加功能。
```html
<my-directive>元素 element</my-directive>
<div my-directive>屬性 attribute</div>
<div class="my-directive">類 class</div>
<!-- directive:my-directive --> <!--注釋 comment-->
```
```javascript
angular.module('myApp',[])
.directive('myDirective', function() {
return {
restrict: 'E',
template: '<a href="http://google.com">Click me to go to Google</a>'
};
});
```
**通過**AngularJS模塊API中的`.directive()`**方法**,我們可以通過傳入一個字符串和一個函數來**注冊**一個新**指令**。
其中字符串是這個指令的名字,指令名應該是駝峰命名風格的,函數應該返回一個對象。
**內置指令** 在AngularJS內部的指令。所有內置指令的命名空間都使用 **ng** 作為前綴。為了**防止命名空間沖突,不要在自定義指令前加ng前綴**。
**聲明指令**本質上是在HTML中通過 **元素**(E)、**類**(C)、**注釋**(M) 或 **屬性**(A) 來添加功能。
我們堅持使用 **屬性** 方式,因為它有比較好的跨瀏覽器兼容性。
注意每個瀏覽器的內置樣式,以便決定指令模板在HTML中是嵌套在聲明元素內,還是替換聲明元素。
#### 用表達式來聲明指令
```html
<my-directive="someExpression">
</my-directive>
<div my-directive="someExpression">
</div>
<div class="my-directive:someExpression">
</div>
<!-- directive: my-directive someExpression -->
```
#### 作用域
```html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Simple app</title>
<link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
<link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.css" rel="stylesheet">
<script src="angular.min.js"></script>
</head>
<body>
{{child}}
<input type="text" name="child" ng-model="child" />
<div ng-controller="ParentCtrl">
{{child}} <input type="text" name="child" ng-model="child" />
<div ng-controller="ChildCtrl">
{{child}} <input type="text" name="child" ng-model="child" />
</div>
</div>
<script type="text/javascript">
angular.module('myApp',[])
.run(function($rootScope){
$rootScope.child = 'root';
})
.controller('ParentCtrl', function($scope){
$scope.child = 'parent';
})
.controller('ChildCtrl', function($scope){
$scope.child = 'child';
});
</script>
</body>
</html>
```
### 向指令中傳遞數據
```html
<div my-directive some-attr="someProperty with @ binding"></div>
```
```javascript
scope: {
someProperty: '@someAttr'
}
```
> 示例
```html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Simple app</title>
<meta charset="UTF-8">
<link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet">
<link href="http://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap-theme.css" rel="stylesheet">
<script src="angular.min.js"></script>
</head>
<body>
<div my-directive my-uri="http://google.com" my-link-text="{{user.name}}"></div>
<script type="text/javascript">
angular.module('myApp',[])
.directive('myDirective', function(){
return {
restrict : 'A',
replace : true,
scope : {
myUrl : '@myUri',
myLinkText : '@'
},
template: '<a href="{{ myUrl }}">{{ myLinkText }}</a>'
};
});
</script>
</body>
</html>
```