angularjs – app.controller vs angular.js中的函数

前端之家收集整理的这篇文章主要介绍了angularjs – app.controller vs angular.js中的函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在学习angular.js,并想知道什么时候应该使用app.controller(“MyCtrl”,…),当使用函数MyCtrl($ scope){…}时。

我看到在这个例子中的两种方法没有大的区别(link to a plunker):

index.html:

@H_403_5@<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:

@H_403_5@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并使用它(而不是使用这个,你可以在第二种方法中做)。

方法一和方法二的区别在于如何支持缩小。在前者中,你可以提供一个注入的参数数组,而在后者中你可以修改$ inject。这当然有点技术,但强烈建议支持缩小。请参阅文档中的A note on minification

前者也没有在全局范围中命名函数,这通常是一件好事!

猜你在找的Angularjs相关文章