I'm learning angular.js, and wonder when app.controller("MyCtrl",...)
should be used and when function MyCtrl($scope){...}
should be used.
I see no big differences between the two approaches in this example (link to a 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>
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;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…