# 控制器（controller）

## angular controller

* 在angular中，controller是⼀一个javascript 函数（type/class），被⽤用作扩展除了root scope在外的angularscope的实例。
* 也可以通过module.controller(name, constructor)
* @see $controllerProvider.register().
* controller可以用作：

  设置scope对象的初始状态。

  增加行为到scope中。

## 正确的使用controller

* controller不应该尝试做太多的事情。它应该仅仅包含单个视图所需要的业务逻辑
* 保持Controller的简单性，常见办法是抽出那些不属于controller的⼯工作到service中，在controller通过依赖注入来使用这些service

不要在Controller中做以下的事情：

1. 任何类型的DOM操作 - controller应该仅仅包含业务逻辑，任何表现逻辑放到controller中，大大地影响了应用逻辑的可测试性。angular为了自动操作（更新）DOM，提供的数据绑定。如果希望执行我们自定义的DOM操作，可以把表现逻辑抽取到directive中。
2. Input formatting（输入格式化） - 使用angular form controls 代替。
3. Output filtering （输出格式化过滤） - 使⽤用angular filters 代替。
4. 执⾏行⽆无状态或有状态的、controller共享的代码 - 使用angular services 代替。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/angularjs/controller.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
