> For the complete documentation index, see [llms.txt](https://xiaoxiami.gitbook.io/angularjs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://xiaoxiami.gitbook.io/angularjs/zhi_ling/angular_zi_ding_yi_zhi_ling/controller_and-and_controllasshu_xing.md).

# controller && controllAs属性

* controller 他会暴露一个API，利⽤用这个API可以在多个指令之间通过依赖注入进行通信
* controller($scope,$element,$attrs,$transclude)
* controllerAs 是给controller起个别名，方便使用
* require 可以将其他指令传递给自己

| 选项             | 用法                                    |
| -------------- | ------------------------------------- |
| directiveName  | 通过驼峰法的命名指定了控制器应该带有哪一条指令,默认会从同一个元素上的指令 |
| ^directiveName | 在父级查找指令                               |
| ?directiveName | 表示指令是可选的，如果找不到，不需要抛出异常                |

**例子：**

index.html

```markup
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">

</head>
<body>
<div ng-app="myApp">

    <div ng-controller="firstController">

        <div book-list>

        </div>

    </div>
</div>

<script src="//cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
<script type="text/javascript" src="app/index.js"></script>
</body>
</html>
```

app/index.js

```javascript
angular.module('myApp', [])

    .directive('bookList', function () {
        return {
            restrict: 'ECAM',
            controller: function ($scope) {
                $scope.books = [
                    {
                        name: 'php'
                    },
                    {
                        name: 'javascript'
                    },
                    {
                        name: 'java'
                    }
                ];
                $scope.addBook = function(){

                }
                this.addBook = function(){
                    // ...
                }
            },
            controllerAs:'bookListController',
            template: '<ul><li ng-repeat="book in books">{{book.name}}</li></ul>',
            replace:true,
            link:function(scope,iEelement,iAttrs,bookListController){
                iEelement.on('click',bookListController.addBook)
            }
        }

    })

    .controller('firstController', ['$scope', function ($scope) {
        // console.log($scope);
    }]);
```
