这是preferred定义一个AngularJS控制器的方式吗? [英] Which is the preferred way of defining an AngularJS controller?
问题描述
作为一个例子,我们有这个 index.html的
code:
<!DOCTYPE HTML>
< HTML NG-应用=样品>
< HEAD>
...
< /头>
<身体GT;
< DIV NG控制器=myController的>
...
<脚本SRC =JS /模块/ app.js>< / SCRIPT>
< / DIV>
< /身体GT;
< / HTML>
和 app.js
我们有一个模块和控制器:
VAR应用= angular.module('样品',[]);//这里控制器
所以我的问题是这样的,我已经看到了两种类型的定义控制器,作为控制器,并作为一个普通的功能:
app.controller('myController的',函数(参数){
...
});
或
VAR = myController的功能(参数){
...
};
哪一个应该使用,为什么?我曾多见于基于角code中使用的第一个,但即使在教程我所遇到的第二位。我个人不使用第二个,因为我看过它污染了全局命名空间。
另一个问题我已经是我所见过这种用法的控制器:
app.controller('myController的',['$范围,$ HTTP',函数($范围,$ HTTP){
...
}]);
为什么我们需要的阵列?我们难道不能只用论据呢?
app.controller('myController的',['$范围,$ HTTP',函数($范围, $ HTTP){
这是破坏您的code做了prevent JS minifiers,因为角度依赖名字依赖分辨率。
至于两种风格控制器的
app.controller('myController的',函数(参数){
...
});
VS
VAR = myController的功能(参数){
...
};
app.controller('myController的',myController的);
这是个人喜好问题。有没有功能上的区别。
As an example, we have this index.html
code:
<!DOCTYPE html>
<html ng-app="sample">
<head>
...
</head>
<body>
<div ng-controller="myController">
...
<script src="js/modules/app.js"></script>
</div>
</body>
</html>
and in app.js
we have a module and a controller:
var app = angular.module('sample', []);
// controller here
So my question is that, I have seen controllers defined in two types, as a controller, and as a plain function:
app.controller('myController', function(args){
...
});
or
var myController = function(args){
...
};
Which one should be used and why? I have mostly seen the first one used in Angular-based code, but even in tutorials I have come across the second. I personally don't use the second, as I have read it 'pollutes the global namespace'.
Another question I have is that I have seen this kind of usage for a controller:
app.controller('myController', ['$scope', '$http', function($scope, $http) {
...
}]);
Why do we need the array? Can't we make do with just the arguments?
app.controller('myController', ['$scope', '$http', function($scope, $http) {
This is done to prevent JS minifiers from breaking your code, because angular relies on names for dependency resolutions.
As for the two styles of controller
app.controller('myController', function(args){
...
});
vs
var myController = function(args){
...
};
app.controller('myController', myController);
It's a matter of personal taste. There's no functional difference.
这篇关于这是preferred定义一个AngularJS控制器的方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!