Angularjs - Best practices for controllers / routing / partials - angularjs

So I am just starting out with angularjs and web development in general and had a few questions regarding the best practices. Some of my questions are actually more related to web development in general.
1) When to use partials and when to use a different page instead. E.g Is is good to embed about.html as a partial in index.html or have a separate page?
2) What is the best way to share data between controllers? Right now I am using query parameters in the route.
3) Should I be using one controller for multiple partials?
Thanks!

Angular is a single page app framework, so you only want to use one html 'page' in most cases. There may be exceptions but unless your project is very large you won't need to use more than one.
Services are the recommended way of doing this. Services return a singleton object, and you can inject references to them using angular's dependency injection. It keeps everything modular, too. Query params are definitely not what you want to use. For calling events between controllers you might also use $scope.$broadcast().
Potentially, you might have an overall AppController for example that encompasses elements that have their own controllers (in their own directives, or using ng-controller). On the subject of directives, remember to use them to bundle re-usable components up. Directives have their own templates and controllers, and using them makes your code much more modular and easier to maintain/test.

Related

Should I have more angular services or controllers?

I am developing an angular web game where I have a bunch of quests that use a single html template for the view. The problem I have is how to organize the Angular code.
Should I have only one controller (which will hold the non-quest-specific logic) and uses a bunch of services (one for each quest-specific logic)? The controller would probably have a big if/else block to use the right service for the chosen quest.
Or should I have one controller for each quest? That way we can use fewer services overall and share them among the various controllers for the quests.
Which one makes more sense and would potentially have the fewest code duplication? Could there be a better alternative to both?
I just suggest you to go for a controller per unit and build the services thinking as elements that you can share between controllers structuring them as functional independent shareable elements.
Quest 1 = controller 1 -> inject all services needed for that quest
Quest 2 = controller 2 -> inject all services needed for this one
.......
You can't share code between controllers. If you want to have less duplicated code you should create services so you can share code between them and the controllers.
A good description of angular controllers vs. angular services can be found in an earlier post
I would recommend using a controller for each quest. Inject services into each controller that are relevant to that particular quest. Although you'll still need to write services to share that data/logic with the controller, you can avoid the unnecessary service injections as well as that massive if/esle block

When should multiple controllers be used in the same page in angularjs?

I would like to know when does it make sense to use multiple controllers on the same page in angularjs. Also, when should one think about separating a controller into multiple controllers?
You should largely have your functionality in providers (services or factories typically) and your controllers should have very little in them aside from getting the providers injected (and exposing models and functions for use in the view) and possibly some view specific functionality (configuration for directives used only in one place etc.). You can have multiple controllers on the page if you decide to build the views within a page to be portable.
If you have one controller that shares the functionality needed for disparate parts of a page and later decide to move one part of the view to another route/state/view then you'll need to piece apart the controller. I don't think there are any hard rules really but if your controller is more than 100 lines you're probably making it responsible for too much and should "promote" some things to be handled by providers and/or start splitting things up a bit more.
The answer would be dependent on your page requirement. Having multiple controllers can easily be done.. But issues pop-up when you wanted to have page flows.
Controllers are just a part of AngularJS.. Usage of services, factories and filters is a recommended way of splitting your code along with controllers. If multiple controllers per page becomes imperative.. try utilizing directives. Also consider using Views provider by UI router.
I use multiple controllers when my page has got multiple pop-ups with complex functionality and i want separate controllers for them so that logic behind each-pop is in its own controller.
Similarly, I create separate controllers for sidebars and header and footers on the same page.
These are few examples which comes in my mind when using multiple controllers on same page makes sense.
But as others have mentioned, you should use providers and services/factory for splitting your code.

Why is AngularJS considered MV*

I have worked with MVC on the back-end (Rails), and am currently working with MVC(MV*) on the front-end (Angular). I have seen Angular as considered an MV* pattern, but why is it considered that exactly?
Using Angular, I understand the separation of concerns, with Views (templates), Controllers, and use Services to serve up data. In this case, the model (data store) via ng-model makes sense for front-end temporary storage, but the actual persistence (when a POST or PUT is made to an API) seems to be the wildcard. As the way data can be persisted, could be handled differently (database, firebase, etc..).
It seems to me that *VC is more appropriate based on my understanding, as Controllers in Angular are better defined than Models.
There must be something core about the MV* pattern that I am missing or confused about, any clarification is greatly appreciated.
Here are a few ways * can be chosen in Angular:
Controller:
ngModelController
$controller
View Model:
dependent expressions
directive attributes
Presenter:
WebGL Directive
Presentation-Abstraction-Controller
module per iframe
Important thing is that UI and Models are the common denominator. Build interesting UI without breaking app and build interesting business logic without breaking UI.
References
Keynote for BackboneConf with Jeremy Ashkenas

why / when to use multiple controller - Angularjs

I started working with AngularJs recently.
Looking to understand the reason for using multiple controller, I found different site explaning how to use multiple controller (AngularJS site). But what I'm actually looking for is a rationnal for using multiple controller.
So my question is : Why or when should we use multiple controller in a project? and the subquestion that is tied to this question: is it a good pratice to use multiple controller in an Angular project.
That's also an MVC question as angular extends this pattern. In Apple's View Controller Programming Guide for iOS, it says :
Every view is controlled by only one view controller.
So the idea in MVC pattern is to separate views. By having 1 Controller per View it makes it easier to achieve this. it simplifies the organization of controllers that serve one module. You do not suffer from code smells.
Also, it is important for routing issues in app.js for angular case. It clarifies structure for other developers that will have look at project. Using testacular in angularjs, unit testing is great, having multiple controllers makes unit testing easier.
Edit :
You would also most likely need more controllers for further functionalities. For example a Auth Controller where users can create new accounts. In addition to this you need a superadmin view where you can edit the resources with higher privileges. In such a case it is quite common to have separate controller. Scope and security issues has to change.
It is just a very good pratice to use 1 controller per 1 view. So for example you should have seperate controller for /home view, another one for /gallery, and another /contact.
It forces you as a developer to organise your code, so that you can take advantage of using services, filters etc.
Also it is easier to write unit tests because you can see what is covered and what is not.

What is the difference between service, directive and module?

I have been reading a lot of docs, and I'm getting more and more confused.
I basically can't figure out the difference between a
service
directive
module
I see a lot of custom components. Sometimes they're using directives, sometimes services. It always starts with a module. Can someone explain with an example what the difference is between these three types?
From my own personal notes (mostly snippets from the docs, google group posts, and SO posts):
Modules
provide a way to namespace/group services, directives, filters, configuration information and initialization code
help avoid global variables
are used to configure the $injector, allowing the things defined by the module (or the whole module itself) to be injected elsewhere (Dependency Injection stuff)
Angular modules are not related to CommonJS or Require.js. As opposed to AMD or Require.js modules, Angular modules don't try to solve the problem of script load ordering or lazy script fetching. These goals are orthogonal and both module systems can live side by side and fulfill their goals (so the docs claim).
Services
are singletons, so there is only one instance of each service you define. As singletons, they are not affected by scopes, and hence can be accessed by (shared with) multiple views/controllers/directives/other services
You can (and probably should) create custom services when
two or more things need access to the same data (don't use root scope) or you just want to neatly encapsulate your data
you want to encapsulate interactions with, say, a web server (extend $resource or $http in your service)
Built-in services start with '$'.
To use a service, dependency injection is required on the dependent (e.g., on the controller, or another service, or a directive).
Directives (some of the items below say essentially the same thing, but I've found that sometimes a slightly different wording helps a lot)
are responsible for updating the DOM when the state of the model changes
extend HTML vocabulary = teach HTML new tricks. Angular comes with a built in set of directives (e.g., ng-* stuff) which are useful for building web applications but you can add your own such that HTML can be turned into a declarative Domain Specific Language (DSL). E.g., the <tabs> and <pane> elements on the Angular home page demo "Creating Components".
Non-obvious built-in directives (because they don't start with "ng"): a, form, input, script, select, textarea. Under Angular, these all do more than normal!
Directives allow you to "componentize HTML". Directives are often better than ng-include. E.g., when you start writing lots of HTML with mainly data-binding, refactor that HTML into (reusable) directives.
The Angular compiler allows you to attach behavior to any HTML element or attribute and even create new HTML elements or attributes with custom behavior. Angular calls these behavior extensions directives.
When you boil it all down, a directive is just a function which executes when the Angular compiler encounters it in the DOM.
A directive is a behavior or DOM transformation which is triggered by a presence of an attribute, an element name, a class name, or a name in a comment. Directive is a behavior which should be triggered when specific HTML constructs are encountered in the (HTML) compilation process. The directives can be placed in element names, attributes, class names, as well as comments.
Most directives are restricted to attribute only. E.g., DoubleClick only uses custom attribute directives.
see also What is an angularjs directive?
Define and group Angular things (dependency injection stuff) in modules.
Share data and wrap web server interaction in services.
Extend HTML and do DOM manipulation in directives.
And make Controllers as "thin" as possible.
Think of a module as being a place to wire up a number of other things, such as directives, services, constants etc. Modules can be injected into other modules giving you a high level of reuse.
When writing an angular app, you would have a top-level module which is your application code (without templates).
Services are mainly a way to communicate between controllers, but you can inject one service into another. Services are often used as a way to get to your data stores and people will wrap the angular APIs, such as ngResource. This technique is useful since it makes testing (particularly mocking) quite easy. You can have services for doing other things like authentication, logging etc.
Directives are used for creating widgets or wrapping existing things like jquery plugins. Wrapping existing plugins can be a challenge and the reason you would do this is to establish a two-way data binding between the plugins and angular. If you don't need two-way data binding then you don't need to wrap them.
A directive is also a place for doing DOM manipulation, catching DOM-events etc. You should not be doing DOM-related stuff in controllers or services. Creating directives can get pretty complex. IMHO, I recommend first looking at API for something that can do what you are looking for OR ask Angular's Google Group for advice.

Resources