简体   繁体   English

AngularJS控制器的最佳实践

[英]Best Practice for AngularJS Controller

What is the best way to write a controller in AngularJS? 用AngularJS编写控制器的最佳方法是什么? I've seen it written many different ways and it's confusing on which way is better then the rest. 我已经看到它以多种不同的方式编写,并且混淆了哪种方法比其他方法更好。

Personally I write it like this, 我个人是这样写的

var app = angular.module('app'); // app is created elsewhere, just referencing it

var MainController = function($scope) {
    // Do Stuff
}

app.controller("MainController", [MainController]);

I think writing it this way is the cleanest way to write it. 我认为以这种方式编写是最干净的方式。 Everything is separated so it's easier to read. 一切都是分开的,因此更易于阅读。

The most common way I've seen it written is like this, 我看过的最普通的写法是这样的,

app.controller("EventController", function EventController($scope) {
    // Do stuff
}

I would like to know, if there any pitfalls in the future that would happen if I keep writing them the way I prefer? 我想知道,如果我继续以自己喜欢的方式编写它们,将来是否会遇到陷阱? Why is one way better than the other? 为什么一种方法比另一种更好?

The difference between the two, (besides what you are already used to) is that the first is a function that is declared once, and the second is an inline-function. 两者之间的区别(除了您已经习惯的)是,第一个是一次声明的函数,第二个是内联函数。

For your reference, here are a few SO Posts about the actual differences, and when to use each of them. 供您参考,这里有一些SO帖子,介绍了实际的差异以及何时使用它们。

Also since you are asking specifically about AngularJS, you should check out the following two styling guides. 另外,由于您是专门询问AngularJS的,因此您应该查看以下两个样式指南。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM