在AngularJS中声明控制器

Gam*_*iac 11 javascript function angularjs

我在AngularJS教程中看到过,有些人声明他们的控制器函数是这样的:

function FirstController($scrope) {
    // do something with $scope
}
Run Code Online (Sandbox Code Playgroud)

和其他人这样做:

var FirstController = function ($scope) {
    // do something with scope
}
Run Code Online (Sandbox Code Playgroud)

哪种方式是在JS文件中声明控制器的最佳方式,哪种方式最适合使用最新版本的AngularJS(现在为1.0.7),哪种方法最佳?或者它真的不重要吗?

Ros*_*len 22

您应该遵循它们提供的第二个示例,它使用字符串来标识您的控制器,而不是可能的全局函数.使用Array语法,以便您可以缩小代码,而无需担心minifier重命名函数参数.

var myApp = angular.module('myApp');

myApp.controller('GreetingCtrl', ['$scope', function($scope) {
    $scope.greeting = 'Hola!';
}]);
Run Code Online (Sandbox Code Playgroud)

资料来源:http://docs.angularjs.org/guide/controller

  • 公平地说,Angular文档中的第一个示例显示了原始海报输入的确切内容.Angular团队应该删除这个例子,因为这是不好的做法. (8认同)
  • 老实说,除非您通读 angularJS 文档并了解正在发生的事情,否则这确实看起来令人困惑。 (2认同)