- 控制器的定义
- 控制器的初始化
- 控制器的作用域和范围
第一点:控制器必须定义在模块中,不可以定义在$rootScope中,这样会污染全局作用域。定义的步骤:首先定义一个模块
app,然后定义一个控制器,最后实现这个控制器。
<html ng-app = "app"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="../angular-1.6.9/angular.js"></script> </head> <body ng-controller="initController as init"> <div> price: <input type="number" ng-model="price"/><br> amount: <input type="number" ng-model="amount"/><br> total: {{init.total()}} </div> <script type="text/javascript"> function initController($scope) { $scope.price = 8.0; $scope.amount = 10; this.total = function() { return $scope.price * $scope.amount; } } var app = angular.module("app", []); app.controller("initController", initController); </script> </body> </html>
第二点:这里控制器的初始化是以构造函数被执行的形式完成的。
第三点:也是最难的一点,其实也不难,只是如果不了解作用域的概念,那么出现错误,代码达不到预期的效果,真是不知道怎么改正。控制器是定义在模块中的,那么如果不在模块的作用域范围内调用控制器,那肯定是无效的。比如对以上代码稍作修改
<html ng-app> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="../angular-1.6.9/angular.js"></script> </head> <body ng-controller="initController as init"> <div> price: <input type="number" ng-model="price"/><br> amount: <input type="number" ng-model="amount"/><br> total: {{init.total()}} </div> <script type="text/javascript"> function initController($scope) { $scope.price = 8.0; $scope.amount = 10; this.total = function() { return $scope.price * $scope.amount; } } var app = angular.module("app", []); app.controller("initController", initController); </script> </body> </html>
运行的结果是
这是什么意思?意思是调用控制器中的方法失败,为什么?因为从app.controller("initController", initController)可以看出
initController属于app模块,同时init是
initController的名称,但是纵观html代码,根本没有app模块。所以不行。
突然发现还有一个小细节:代码修改一下
<html ng-app = "app"> <head> <meta charset="utf-8"> <title></title> <script type="text/javascript" src="../angular-1.6.9/angular.js"></script> </head> <body> <div ng-controller="initController as init"> price: <input type="number" ng-model="price"/><br> amount: <input type="number" ng-model="amount"/><br> total: {{init.total()}} </div> <script type="text/javascript"> function initController($scope) { $scope.price = 8.0; $scope.amount = 10; $scope.total = function() { return $scope.price * $scope.amount; } } var app = angular.module("app", []); app.controller("initController", initController); </script> </body> </html>这样行不行?不行!
this.total = function() { return $scope.price * $scope.amount;}的意思是将total()方法挂在当前作用控制器的作用域上。但是
$scope.total = function() {return $scope.price * $scope.amount;}的意思却是将total()方法挂在$scope上。显然$scope作用域要大于initController作用域的,你是不可以在一个相对较小的作用域上去访问一个超出你作用域范围上的对象的。这些细节的挖掘是十分耗费时间的,尤其是出入门的菜鸟。理解了细节,才是对概念的真正把握。