我正在学习 angular.js,想知道什么时候app.controller("MyCtrl",...)
应该使用,什么时候function MyCtrl($scope){...}
应该使用。
在此示例中,我认为这两种方法之间没有太大区别(指向 plunker 的链接):
索引.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>
例子.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;
}
}