我正在学习angular.js,想知道什么时候app.controller("MyCtrl",...)
应该使用什么时候function MyCtrl($scope){...}
应该使用。
在此示例中,我发现两种方法之间没有太大差异(链接到插件):
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;
}
}
在这两种用法中,推荐的方法都是注入$scope
和使用该方法(而不是使用this
,您也可以在第二种方法中使用)。
方法一和方法二的区别在于如何支持缩小。在前者中,您可以提供注入参数的数组,而在后者中,您可以修改$inject
。这当然有点技术性,但强烈建议您支持缩小。请参阅文档中有关缩小的说明。
前者也没有在全局范围内命名该函数,这通常是一件好事!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句