我正在学习angular.js,并想知道什么时候app.controller("MyCtrl",...)应该使用以及什么时候function MyCtrl($scope){...}应该使用.
我看到这个例子中两种方法之间没有太大的区别(链接到一个plunker):
index.html:
<body ng-app="myApp">
<div ng-controller="FirstCtrl as app1">
<button class="btn" ng-model="app1.count"
ng-click="app1.increment()">
Click to increment</button>
{{ app1.count }}
</div>
<div ng-controller="SecondCtrl">
<button class="btn" ng-model="count"
ng-click="increment()">
Click to increment</button>
{{ count }}
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>
<script type="text/javascript" src="example.js"></script>
</body>
Run Code Online (Sandbox Code Playgroud)
example.js:
var app = angular.module("myApp", []);
app.controller("FirstCtrl",function () {
this.count = 0;
this.increment = function (){
this.count = this.count + 1;
}
});
function SecondCtrl($scope){
$scope.count = 0;
$scope.increment = function (){
$scope.count = $scope.count + 1;
}
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*ani 17
使用基于模块的控制器声明的主要原因是
Nit*_*mar 12
通常,在创建应用程序时,需要为Angular范围设置初始状态.
Angular将控制器构造函数(在JavaScript的Function#apply意义上)应用于新的Angular范围对象,该对象设置初始范围状态.这意味着Angular永远不会创建控制器类型的实例(通过在控制器构造函数上调用new运算符).构造函数始终应用于现有范围对象.
您可以通过创建模型属性来设置范围的初始状态.例如:
function GreetingCtrl($scope) {
$scope.greeting = 'Hola!';
}
Run Code Online (Sandbox Code Playgroud)
GreetingCtrl控制器创建一个可以在模板中引用的问候模型.
注意:文档中的许多示例都显示了在全局范围内创建函数.这仅用于演示目的 - 在实际应用程序中,您应该为您的应用程序使用Angular模块的.controller方法,如下所示:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingCtrl', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
Run Code Online (Sandbox Code Playgroud)
另请注意,我们使用数组表示法显式指定控制器对Angular提供的$ scope服务的依赖性.
| 归档时间: |
|
| 查看次数: |
27257 次 |
| 最近记录: |