Page 315 - AngularJS权威教程
P. 315
21.3 控制器 295
作用域的蔓延是Angular框架最令人困惑的一个方面,我们在控制器的$scope中定义了很多 19
功能。编写Web应用时,有时会发现控制器的大小逐渐严重失控。
可以移出处理DOM的方法,以减少控制器的大小。把功能移动到自定义指令中,大幅降低 20
了为判断是否公开特定视图或者格式化一个值的需要。
因为我们在视图里绑定了$scope上的值,控制器没有必要负责持有DOM对象所需的状态值。 21
比如,我们可以删除控制器中处理显示值的方法。
假设我们有一个登录页面,根据用户的选择的状态显示登录表单或者注册表单,把这个页面 22
命名为showLoginForm:
23
angular.module('myApp', [])
.controller('LoginController', function($scope) {
// 如果为true,显示为登录表单
// 如果为false,显示为注册表单 24
$scope.showLoginForm = true;
$scope.sendLogin = function() {}
$scope.sendRegister = function() {} 25
});
在我们的HTML里面,可能以如下方式设置LoginController的功能:
26
<div ng-show="showLoginForm">
<form ng-submit="runLogin()"></form>
</div> 27
<div ng-show="!showLoginForm">
<form ng-submit="runRegister()"></form>
</div>
28
尽管这个例子很普通(在我们的$scope里只有一个多余的变量),当我们的视图变得越来越
复杂时,这种变量的数量会按指数级增长。
29
使用指令,我们可以把这个值去掉。例如:
angular.module('myApp', []) 30
.directive('loginForm', function() {
return {
scope: { 31
onLogin: '&',
onRegister: '&'
},
templateUrl: '/templates/loginRegForms.html', 32
link: function(scope, ele, attrs) {
scope.showLoginForm = true;
scope.submitLogin = function() { 33
scope.onLogin({user: scope.loginUser});
}
scope.submitRegister = function() {
scope.onRegister({user: scope.newUser}); 34
}
}
} 35
});
angular.module('myApp', [])
.controller('LoginController', function($scope) {
$scope.sendLogin = function() {} 36