Understanding Controllers (控制器)
In Angular, a Controller is a JavaScript constructor function that is used to augment the Angular Scope.
When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller’s constructor function. A new child scope will be available as an injectable parameter to the Controller’s constructor function as $scope.
Use controllers to:
- Set up the initial state of the $scope object.
- Add behavior to the $scope object.
Do not use controllers to:
- Manipulate DOM ---- Controllers should contain only business logic. Putting any presentation logic into Controllers significantly affects its testability. Angular has data binding for most cases and directives to encapsulate manual DOM manipulation.
- Format input ---- Use angular form controls instead.
- Filter output ---- Use angular filters instead.
- Share code or state across controllers ---- Use angular services instead.
- Manage the life-cycle of other components (for example, to create service instances).
在Angular里,控制器就是一个用来增强Scope的JavaScript的构造函数。
当一个控制器通过ng-controller指令被附在DOM上的时候,Angular就会用这个指定的构造函数,初始化一个新的控制器实例。同时,1个子scope会以$scope的名字的变量身份,被注入到新的构造函数里。
这些情况下你应该使用控制器:
- 设置$scope对象初始化状态的时候;
- 向$scope对象添加行为的时候。
这些情况你不应该使用控制器:
- 操纵DOM的时候 ---- 控制器里就应该只有业务逻辑。任何把展示的逻辑放进控制器的行为,都会大大影响其可测试性。几乎所有情况下,操纵DOM的操作都可以被数据绑定和指令完成;
- 格式化输入 ---- 用Angular提供的表单控制吧;
- 过滤输出 ---- 用Angular的过滤器不是很棒?
- 在控制器间共享代码和状态 ---- 用Angular的服务好吗?
- 管理其它组件的生命周期 (比方说创建服务实例)
学习控制器
时间: 2024-10-13 10:08:06