这是来自ThoughtWorks巴西团队分享的一些使用AngularJS的一些技巧和教训。经验内容包括结构、依赖注入、HTML扩展、作用域和模块。这是2014年ThoughtWorks Insights网站最受欢迎的内容,没有之一。
A team of us in the Porto Alegre office has been using AngularJS for a while now, and it has been learning curve. We want to share some practices that we have learned along the way that can help you start your AngularJS application on the right foot!. Learn from our mistakes! This article has no intention of setting rules or having the absolute truth but only to give some useful tips and lessons learned when writing AngularJS applications. Here are some good practices for AngularJS applications separated in five categories: #1 Structure: When we start to build an AngularJS application sometimes we don’t know exactly how to organise our files or even know what files we need. For this, the AngularJS team recommends two solutions: 1) Use the angular-seed (https://github.com/angular/angular-seed) project, which is basically a skeleton of a typical AngularJS application. You just need to clone the repository and you are good to go! 2) The other recommendation is to use yeoman (http://yeoman.io/) which is a tool that will basically create the skeleton and add other tools such as bower and grunt, which are widely used in the development of javascript applications according to the user preferences. You need to be very careful with these tools that seem to be very useful in the beginning. Why is that? Because you need to think first on what your project needs are. For example, angular-seed will create a folder named ‘app’ where all the static deployable files are and inside we will have a folder named ‘js’ with all our javascript files like ‘controllers.js’, ‘services.js’, etc… It depends a lot in the nature of the application we are building but there will be cases in which it is better to separate files for what they mean for the business rather that having them for what kind of component they are inside the framework we are using. In this case, for example, if we are building a sales module we could have files like ‘product-controller.js’ or ‘product-service.js’ and have folders inside our ‘js’ folder with the modules of the business. #2 Dependency Injection: The AngularJS injector is pretty powerful and can be very useful if used correctly. It’s in charge of creating components, resolving their dependencies and providing the components when required. What benefits do we have when we use it? One of the greatest benefits is given when writing tests for our application! If in each component we create, following the AngularJS syntax, we can require other components and it will take care of resolving these dependencies for us, then when creating our tests we can just simply create these same components but with dependencies created by us (mocked objects), then we are able to really unit test our application and have a good coverage.