Where should I put AngularJS Factories & Services? - javascript

I'm working to cleanly structure my AngularJS app according to best practices, which includes separating the controllers and app into different script files.
Quick question: where should I put my factories and services? I am asking in the context of having factories & services that will be accessed outside of the scope of a single controller as well as having some that are within the scope of a single controller.

Update: the immediate answer below is no longer correct. Please see the latest addendum (written March 1, 2015) to this answer.
Got it! According to Brian Ford's article on Building Huuuuuuuge Angular Apps, the best practice appears to be to connect services and factories to the app in a separate file, like so:
root-app-folder
├── index.html
├── scripts
│ ├── controllers
│ │ └── main.js
│ │ └── ...
│ ├── directives
│ │ └── myDirective.js
│ │ └── ...
│ ├── filters
│ │ └── myFilter.js
│ │ └── ...
│ ├── services
│ │ └── myService.js
│ │ └── ...
│ ├── vendor
│ │ ├── angular.js
│ │ ├── angular.min.js
│ │ ├── es5-shim.min.js
│ │ └── json3.min.js
│ └── app.js
├── styles
│ └── ...
└── views
├── main.html
└── ...
(PSST! In case you're wondering, Brian Ford is part of the AngularJS team, so his answer seems pretty legit.)
Addition (April 24, 2013)
This just in: Yeoman is a fantastic tool for generating apps with the proper directory structure for big, functional Angular apps. It even has Grunt & Bower packed in!
Addendum (March 1, 2015)
According to a comment via PaoloCargnin, Google actually recommends a different structure, as detailed by this document. The structure should look like this:
sampleapp/
app.css
app.js //top-level configuration, route def’ns for the app
app-controller.js
app-controller_test.js
components/
adminlogin/
adminlogin.css //styles only used by this component
adminlogin.js //optional file for module definition
adminlogin-directive.js
adminlogin-directive_test.js
private-export-filter/
private-export-filter.js
private-export-filter_test.js
userlogin/
somefilter.js
somefilter_test.js
userlogin.js
userlogin.css
userlogin.html
userlogin-directive.js
userlogin-directive_test.js
userlogin-service.js
userlogin-service_test.js
index.html
subsection1/
subsection1.js
subsection1-controller.js
subsection1-controller_test.js
subsection1_test.js
subsection1-1/
subsection1-1.css
subsection1-1.html
subsection1-1.js
subsection1-1-controller.js
subsection1-1-controller_test.js
subsection1-2/
subsection2/
subsection2.css
subsection2.html
subsection2.js
subsection2-controller.js
subsection2-controller_test.js
subsection3/
subsection3-1/
etc...

Related

How to exclude files when create build in react js

Currently I am working one react js project. there i create two different app in one application (eg. app1 and app2).
i have render two app base on condition i want to deploy this app one by one firstly create build with app1 and
after few time create build with app2.
so what i want to do is when i m create build for folder app1 in that time i don't want move app2 folder in build.
and also don't want to move unnecessary components with build.
so is there any way to exclude my app2 folder from build and others file ? how can i achieve that?
here is my app structure.
.
└── myApplication/
├── public
└── src/
├── app1/
│ ├── assets
│ ├── service
│ ├── hooks
│ ├── components
│ └── index.js
├── app2/
│ ├── assets
│ ├── service
│ ├── hooks
│ ├── components
│ └── index.js
├── router.js
├── App.js
├── index.js
├── app.css
├── service
└── hooks

Share common dependencies between contexts

Premise
Let's say I have two different AMD-based AngularJS apps, each of them with their own sets of controllers, directives, services, etc. Each of them are bundled in their own dist/{app-name}.min.js and loaded in <script> tags in the same HTML page (this is all in the context of a CMS that then contains these apps among other things)
Now the apps end up sharing some of the services, directives, and vendor libraries like angular itself, moment, jQuery, etc, so I've made another folder for all of these resources, which results in a bundle that will be added to the page before the js bundles of the apps:
<script src="/some-path/dist/shared-resources.min.js"></script>
<script src="/some-path/dist/first-app.min.js"></script>
<script src="/some-path/dist/second-app.min.js"></script>
This is the resulting folder structure:
.
├── shared-resources/
│ ├── dist/
│ ├── src/
│ │ └── common/
│ │ ├── directives/
│ │ ├── modules/
│ │ ├── services/
│ │ └── vendor/
│ └── build.js
│
├── first-app
│ ├── dist/
│ ├── src/
│ │ ├── first-app/
│ │ │ ├── controllers/
│ │ │ ├── modules/
│ │ │ ├── services/
│ │ │ ├── directives/
│ │ │ └── app.js
│ │ └── first-app.js
│ └── build.js
│
└── second-app
├── dist/
├── src/
│ ├── second-app/
│ │ ├── controllers/
│ │ ├── modules/
│ │ ├── services/
│ │ ├── vendor/
│ │ └── app.js
│ └── second-app.js
└── build.js
This is an example of what the build.js file for the common modules looks like
({
baseUrl: 'src',
removeCombined: true,
out: 'dist/shared-resources.min.js',
paths: { // forcing a `common/{modulename}` convention
'common/jquery': 'common/vendor/jquery.min',
'common/moment': 'common/vendor/moment.min',
'common/angular': 'common/vendor/angular/angular.min',
},
shim: {
'common/angular': {
exports: 'angular',
}
},
include: [
'common/modules/vendors', // Just a bundle of every vendor modules
'common/directives/common-directive',
'common/services/common-service'
],
})
Now my intention was to have all the shared modules being namespaced with common/, so each of the apps could require common/angular, common/directives/common-directive, and so on, and then exclude the common path when creating their bundle (since all the common modules are already present in the shared-resources.js bundle), for example:
// first-app/src/first-app/controllers/app-controller.js
define([
'first-app/modules/controllers',
'first-app/services/app-service',
'common/services/common-service'
], function (controllers) {
'use strict';
controllers.controller('AppController', ['CommonService', 'AppService', function (CommonService, AppService) {
CommonService.call();
AppService.call();
}]);
});
// first-app/build.js
({
baseUrl: 'src',
out: 'dist/first-app.min.js',
paths: {
'common': 'empty:'
},
name: 'first-app',
deps: ['first-app/app']
})
Problem
The problem is how these two apps, which again are both loaded on the page (this can't be avoided), are supposed to correctly look up these common modules.
Given that each of the apps have obviously a different baseUrl, they are put in different RequireJS contexts, otherwise the baseUrl of the second app would override the baseUrl of the first one, causing the incorrect loading of its modules:
// first-app/src/first-app.js
require.config({
context: 'first-app',
baseUrl: 'first-app/src',
})(['fist-app/app']);
// first-app/src/second-app.js
require.config({
context: 'second-app',
baseUrl: 'second-app/src',
})(['second-app/app']);
But putting them in context then causes the look up for the common modules to fail, as the modules are looked in the baseUrl of the context. Actually this happens only for the second app (second in order of loading), while the first app to be included in the page can load the common modules fine
Question
So how should I make the apps to correctly share the common modules? Am I approaching this wrong? Should I use something else than RequireJS?
The context feature of RequireJS is really meant to be used to handle a case where you have to load two conflicting applications on the same page and the conflict cannot be resolved otherwise. The way you've written your code so far may have led you to want to have two baseUrl values, but there is nothing in your question that indicates that you must have two baseUrl values. There are ways to avoid it:
Modules that are part of a logical set of modules should load each other with relative paths. For instance, the module you give as example could be:
// first-app/src/first-app/controllers/app-controller.js
define([
'../modules/controllers',
'../services/app-service',
'common/services/common-service'
], function (controllers) {
paths can be set to make it look like a module is directly under baseUrl even if it is not. You could have:
paths: {
'first-app': 'first-app/src'
'second-app': 'second-app/src'
}
and yes, loading first-app/app will work. RequireJS will transform the path to first-app/src/app.js.

How to structure Redux components/containers

I’m using redux and I’m not sure about how to organize my components, I think the best is to keep them in folders with the name of the main component as the name of the folder and all inner components inside:
components
Common/ things like links, header titles, etc
Form/ buttons, inputs, etc
Player/ all small components forming the player
index.js this one is the top layout component
playBtn.js
artistName.js
songName.js
Episode/ another component
Then, in the containers folder, I’ve one container per page, that are the only ones I'm actually connecting to Redux:
containers/
HomePageApp.js
EpisodePageApp.js
...
and then the actions are one per each top component, instead of one per page, so in the page container that I connect to Redux I pass all the actions of the components used in that page. For example:
actions/
Player.js
Episode.js
...
Am I doing this right? I haven't found much information about it googling, and the ones I've found I think they are limited to small projects.
Thanks!
In the official examples we have several top-level directories:
components for “dumb” React components unaware of Redux;
containers for “smart” React components connected to Redux;
actions for all action creators, where file name corresponds to part of the app;
reducers for all reducers, where file name corresponds to state key;
store for store initialization.
This works well for small and mid-level size apps.
When you want to go more modular and group related functionality together, Ducks or other ways of grouping functionality by domain is a nice alternative way of structuring your Redux modules.
Ultimately choose whatever structure works best for you. There is no way Redux authors can know what’s convenient for you better than you do.
This is more a question about best practices / code style, and there is no clear answer. However, a very neat style was proposed in the React redux boilerplate project. It's very similar to what you currently have.
./react-redux-universal-hot-example
├── bin
├── src
│ ├── components // eg. import { InfoBar } from '../components'
│ │ ├── CounterButton
│ │ ├── GithubButton
│ │ ├── InfoBar
│ │ ├── MiniInfoBar
│ │ ├── SurveyForm
│ │ ├── WidgetForm
│ │ └── __tests__
│ ├── containers // more descriptive, used in official docs/examples...
│ │ ├── About
│ │ ├── App
│ │ ├── Home
│ │ ├── Login
│ │ ├── LoginSuccess
│ │ ├── NotFound
│ │ ├── RequireLogin
│ │ ├── Survey
│ │ ├── Widgets
│ │ └── __tests__
│ │ └── routes.js // routes defined in root
│ ├── redux
│ │ ├── init.js
│ │ ├── middleware
│ │ │ └── clientMiddleware.js // etc
│ │ └── modules // (action/creator/reducer/selector bundles)
│ │ ├── auth.js
│ │ ├── counter.js
│ │ ├── reducer.js
│ │ ├── info.js
│ │ └── widgets.js
│ ├── server
│ │ ├── middleware
│ │ └── actions // proxy to separate REST api...
│ └── utils
│ │ ├── validationUtility.js // utility only (component-level definitions inside respective dir)
│ └── createDevToolsWindow.js // etc
├── static
│ ├── dist
│ └── images
└── webpack
I prefer keeping smart and dumb components in the same file, but use default export for smart component and export for presentation/dumb components. This way you can reduce file noise in your directory structure. Also group your components by "View" i.e. (Administration => [admin.js, adminFoo.js, adminBar.js], Inventory => [inventory.js, inventoryFoo.js, inventoryBar.js], etc).
I have no strong opinion about the component directories, but I like putting the actions, constants and reducers together:
state/
actions/
index.js
...
constants.js
reducers.js
I alias state with with webpack so in the container components I can import {someActionCreator} from 'state/actions';.
This way, all the stateful code in the app resides in a single place.
Note that reducers.js could be split into multiple files simply by making a reducers/ directory like actions/ and you wouldn't have to change any import statements.
In Redux you have one entry point for your actions (actions/ folder) and an entry point for the reducers (reducers/ folder).
If you go with domain-based code structure you simplify domain/feature implementation and maintenance... on the other hand you are complicating component dependencies and app state/logic maintenance.
Where are you gonna put reusable components? inside feature/domain folder? so if you need a reusable component from other feature/domain you need to create a dependency between domains? mmh not so good for large app!
When you have to combine reducers, domain-code-structure takes away what it gave you previously.
You are only creating single redux modules for each domain/feature.
domain-code-structure should be good in some/most cases, but this is not Redux.
I have a boilerplate with react, redux folder structure and it's being used for many company projects. You can check it out here: https://github.com/nlt2390/le-react-redux-duck

File structure for in-browser MVC applications

I'm building an in-browser MVC application which will eventually run on a mobile device via PhoneGap. The app will communicate with the API server but will otherwise be completely independent. When I develop standard server-side MVC applications in Rails, the models, views, and controllers are separated into distinct files and directories. What's the standard practice with in-browser MVC apps? Are the MVC components usually defined within a single JS file, or are they usually separated out?
During the development phase, yes javascript files should be separated and well documented..
You can use requirejs to load your modules/views/collections separately.
Here is a great tutorial about Asynchronous Module Definitions (AMD). It's mainly about how you would organize your application using modules. I suggest you read it.
Below is the sample project structure the tutorial's author uses:
├── js
│ ├── libs
│ │ ├── jquery
│ │ │ ├── jquery.min.js
│ │ ├── backbone
│ │ │ ├── backbone.min.js
│ │ └── underscore
│ │ │ ├── underscore.min.js
│ ├── models
│ │ ├── users.js
│ │ └── projects.js
│ ├── collections
│ │ ├── users.js
│ │ └── projects.js
│ ├── views
│ │ ├── projects
│ │ │ ├── list.js
│ │ │ └── edit.js
│ │ └── users
│ │ ├── list.js
│ │ └── edit.js
│ ├── router.js
│ ├── app.js
│ ├── main.js
│ ├── order.js
│ └── text.js
└── index.html
For the validation/deployment phase, use a grunt-like tool to launch automated tasks. Such as concatenating and minifying javascript files into a single one. (It takes around 30 seconds depending on how you've configured it)
Here is an example of a grunt file.

Optimal directory structure for app -- node + dojo: would this work?

I am trying to work out the best directory structure for a small Dojo application (it's a basic booking system).
I am just about finished writing login/registration.
Here is what I have now:
.
├── app
│ ├── client
│ │ ├── JsonRest.js
│ │ ├── lib
│ │ │ ├── defaultSubmit.js
│ │ │ ├── globals.js
│ │ │ ├── globalWidgets.js
│ │ │ ├── Logger.js
│ │ │ └── stores.js
│ │ ├── login.js
│ │ ├── main.css
│ │ ├── main.js
│ │ ├── register.js
│ │ ├── rrl.css
│ │ ├── TODO.txt
│ │ ├── validators.js
│ │ └── widgets
│ │ ├── _AjaxValidatorMixin.js
│ │ ├── AlertBar.js
│ │ ├── AppMainScreen.js
│ │ ├── BusyButton.js
│ │ ├── css
│ │ │ └── AlertBar.css
│ │ ├── Dashboard.js
│ │ ├── LoginForm.js
│ │ ├── RegisterForm.js
│ │ ├── SearchPage.js
│ │ ├── StackFading.js
│ │ ├── _StackFadingMixin.js
│ │ ├── TabFading.js
│ │ ├── templates
│ │ │ ├── LoginForm.html
│ │ │ ├── RetypePassword.html
│ │ │ └── SearchPage.html
│ │ ├── ValidationEmail.js
│ │ ├── ValidationPassword.js
│ │ ├── ValidationUsername.js
│ │ ├── ValidationWorkspace.js
│ └── server
│ ├── AppErrorHandler.js
│ ├── auth.js
│ ├── db.js
│ ├── globals.js
│ ├── node_modules
│ │ ├── express
│ │ ├── jade
│ │ ├── mongodb
│ │ └── mongoose
│ ├── public
│ │ ├── app -> ../../client/
│ │ └── libs -> ../../../libs
│ ├── routes
│ │ └── routes.js
│ ├── server.js
│ ├── test.js
│ └── views
│ ├── index.jade
│ ├── login.jade
│ └── register.jade
├── libs
├── build-report.txt
├── dojo -> dojo-1.7.1
├── dojo-1.7.1
│ ├── app -> ../../app/client
│ ├── dijit
│ ├── dojox
│ ├── dojo
│ └── util
└── dojo-1.8.0
├── app -> ../../app/client
├── dijit
├── dojox
├── dojo
└── util
The idea behind it is that:
the "app" directory will be in a git repository somewhere (it's about time I make one, actually). It has the directories "client" (all the client-side code) and "server" (the node code).
In "libs" I will add things like dgrid, etc. I also noticed that Dojo 1.8 can be loaded within node (!). I will play with this later -- exciting!
Now, here you can see that I basically used symbolic links to make things work.
SERVER side: Under "public", I had symlinks to "app" and "libs". That way, I can access, from HTML, things like /libs/dojo/dojox/form/resources/BusyButton.css, or (important!) /libs/dojo/dojo/dojo.js and /app/main.js (which then instances AppMainScreen with a simple require(["app/widgets/AppMainScreen" ], function( AppMainScreen){ ...
CLIENT side: I have a symlink to the latest Dojo (my boilerplate still has a problem with Dojo 1.8, so I am still using 1.7 for now). However, in order to make this work within the app:
require(["app/widgets/AppMainScreen" ], function( AppMainScreen){
I have a symlink to "app" within Dojo.
Now: I realise the basics (I think the symlink to "app" within Dojo is solved by simply using DojoConfig, for example). But... well, this is my current 100% unoptimised, never built tree.
I can ask you guys give me the tick of approval for this tree? Will it work once I start "building" things? (I am still miles away from doing it, but I will eventually otherwise my [pregnant] wife will go crazy!). Avoiding that symlink to "app" is one of the things I think I should do (but then again, do I need to?).
Thank you!
Merc.
While not being a fan (nor knowledgable at all) of node, it looks to me as there's a huuge javascript library :)
I'd suggest You should really consider making a buildprofile and use the prefix key to set the location of your scripts. As result of a build, you would automatically get an 'app' folder coexisting with dojo,dijit,dojox.
Actually, i would suggest that once there is a separate repository for your dojo application layer, simply do the checkout within the SDK root, e.g. :
wget download.dojotoolkit.org/dojotoolkit-1.7.2-src.tar.gz -O djsrc.tar.gz && tar xfz djsrc.tar.gz && rm djsrc.tar.gz
cd dojotoolkit-1.7.2-src/
svn checkout http://example/mylibrary app
sh utils/buildscripts/build.sh --profile app/package.profile --release /var/nodejs/docroot/lib/
There is no harm at all in developing your app.widgets somewhere else then in your main document root (/lib). You could simply setup one global variable that tells loader where to look.
If built, nothing should be nescessary, but as far as your current tree goes, try something like this
<script>
var isDevelopement = true;
var dojoConfig = {
packages : (isDevelopement) ? [ name: 'app', location: '/app/client/' ] : []
}
</script>

Categories