[英]Declaring controllers in AngularJS
I've seen that on AngularJS tutorials, that some people declare their controller functions like so: 我在AngularJS教程中看到过,有些人声明他们的控制器函数是这样的:
function FirstController($scrope) {
// do something with $scope
}
and other have done it like this: 和其他人这样做:
var FirstController = function ($scope) {
// do something with scope
}
Which way is the best way to declare a controller in your JS file, that will work best with the latest version of AngularJS ( right now 1.0.7 ), as in what are the best practices? 哪种方式是在JS文件中声明控制器的最佳方式,哪种方式最适合使用最新版本的AngularJS(现在为1.0.7),哪种方法最佳? Or does it not really matter? 或者它真的不重要吗?
You should follow the second example they offer, which uses a string to identify your controller rather than a potentially global function. 您应该遵循它们提供的第二个示例,它使用字符串来标识您的控制器,而不是可能的全局函数。 Use the Array syntax so you can minify your code without worrying about the minifier renaming function parameters. 使用Array语法,以便您可以缩小代码,而无需担心minifier重命名函数参数。
var myApp = angular.module('myApp');
myApp.controller('GreetingCtrl', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
Source: http://docs.angularjs.org/guide/controller 资料来源: http : //docs.angularjs.org/guide/controller
myApp.controller('myControl',['$scope',function($scope){ $scope.controlname = "Something"; }]);
The recommended way of declaring Controllers is using the array notation: 声明控制器的推荐方法是使用数组表示法:
someModule.controller('MyController', ['$scope', 'dep1', 'dep2', function($scope, dep1, dep2) {
...
$scope.aMethod = function() {
...
}
...
}]);
according to angularJS site : https://docs.angularjs.org/guide/di 根据angularJS网站: https ://docs.angularjs.org/guide/di
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.