Best practices to inject custom module in meanjs - angularjs

As I understood there is no classical registration of module, where we can inject our dependencies like:
var myModule = angular.module('myModule', [otherModule]);
However there are file module-name.client.module.js at the root of the directorys
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('module-name');
Can I inject here my module like *.registerModule('module-name', [someModule]); or I should do it in angular.module('articles').config(...)?
But in config I can inject only providers, without factories

As far as i used angular, the best practice to load custom module and external library
is to combine angularjs with requirejs.
It's done in 3 step.
First, load in your main html file a js file which builds the foundation of your system (require.config):
Here you have all the parameters allowed : https://github.com/jrburke/r.js/blob/master/build/example.build.js
Example :
In your html file :
<script src="path/to/require.js" data-main="path/to/yourBuildFile"></script>
In yourBuildFile file :
require.config({
// you can define suitable names for all your external js library
paths:{
// don't put a ".js" at the end of the file
'angular' : 'path/angular',
'underscore' : 'path/underscore-min',
'...': '...',
},
// and other useful things
});
Second, in the same file or in another (see the parameter deps in link above), bootstrap your app:
Like explained here : https://docs.angularjs.org/guide/bootstrap
Example:
// AMD module injection, more info here : http://requirejs.org/docs/whyamd.html
define([ // inject all the external library you need + the definition of your app
'angular',
'require',
'yourpath/yourApp' // don't bother here, it's explained in third point
], function(angular){
// link your app to the document file programatically
angular.bootstrap(document, ['nameOfYourApp']);
});
Third, you define your app (in the "yourpath/yourApp")
Example:
define([
'angular',
// put all path to your directives + controllers + services
], function(angular){ // only specify parameters the library you use in the function
// you create your sublime app :)
angular.module('nameOfYourApp', [
// put all the name of your modules injected above
]);
});
The example above is made for single page application.
You can find other examples for multipage application here
http://requirejs.org/docs/start.html

Related

Add custom headers to all resources in all modules

In my Angular JS site, I have many modules & many resources (From where I consume Rest API)
I want to add a custom header to all outgoing requests in each & every module.
For eg : Here are 2 modules : common & ABC
//---File 1 common.js
angular.module("common",[])
.config(['$httpProvider',
function($httpProvider)
{
$httpProvider.defaults.headers.common['x-access-token'] =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJOYW1lIjoiQWJkdWwiLCJpYXQiOjE0NjUwMzkwMzgsImV4cCI6MTQ2NTEyNTQzOH0.6BMBuEl2dbL736qUqNYXG29UBn_HRyCyWEmMXSG3euE';
}
])
.service("commonApi",['$resource',
function($resource)
{
this.getBankList = function()
{
return $resource('api/emi/banklist:quoteId', { },{}).query();
}
}]);
//---File 2 abc.js
angular.module("abc",[])
.config(['$httpProvider',
function($httpProvider)
{
$httpProvider.defaults.headers.common['x-access-token'] =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJOYW1lIjoiQWJkdWwiLCJpYXQiOjE0NjUwMzkwMzgsImV4cCI6MTQ2NTEyNTQzOH0.6BMBuEl2dbL736qUqNYXG29UBn_HRyCyWEmMXSG3euE';
}
])
.factory('emiModel', ['$resource',
function($resource) {
return $resource('api/emi/QuoteList:quoteId', { }, {
update: { method: 'PUT' }
});
}])
In the above code, I had to add .config to each module & add the header there.
It is quite time consuming to add it in each module & violates DRY principle.
Is there any simple way by which I can add this configuration to all modules in my app without repeating the code ?
For Carity : I used factory & service just to show that i might be using any thing but I still want the header to be passed.
In the above code, I had to add .config to each module & add the
header there.
It is quite time consuming to add it in each module & violates DRY
principle.
This isn't true. Once the module is loaded, Angular doesn't make a difference between them.
config block affects each and every module in the app that has common module loaded. I.e. all of $http calls will be affected with config in this setup:
angular.module("app",["abc", "common"])...
angular.module("abc",[])...
Though it is recommended to load common module in each submodule that depends on config, too. So they don't break in the case when they are loaded apart from app (e.g. in specs).

How to create a bundle using gulp without using "require" everywhere

Thanks for reading. I am new to gulp, so apologizing if its a dumb question. I have an AngularJS project with the following folder structure:
app/
app.js
modules/
mod1/
index.js
mod1.js
another.js
mod2/
... same structure as mod1
To create a bundle using browserify I am using this:
gulp.task('bundle', function() {
return browserify('app/app.js')
.bundle()
.pipe(vinylSource('bundle.js'))
.pipe(gulp.dest('public/js'));
});
To make this work, I have include require('mod1') ..require('another') and so on.
I always have to make sure that I am requiring the script that I need to use.
My goal is to create a bundle that includes all javascript file inside my app folder starting from app.js without getting into dependency conflicts and without me writing require('somefile').
You can get that by just using the gulp-concat plugin.
You just specify the paths to search. Because you're using angular and need the modules defined before everything else, I'd add the app first, then all the module definitions, then remaining directives and controllers etc after.
var gulp = require('gulp');
var concat = require('gulp-concat');
gulp.task('app-js', function() {
return gulp.src([
'./app/app.js',
'./app/**/mod*.js',
'./app/**/*.js',
])
.pipe(concat('bundle.js'))
.pipe(gulp.dest('public/js'))
});

Angular - Issue in moving service into separate file

I have a service with a few methods:
function userService($http, API, auth) {
....
}
and then used in my module like:
var app = angular.module('app', ['ngRoute'])
.service('user', userService)
...
All of this is in my app.js file, I want to separate things so its easier to maintain. I'm trying to use the line .service('user', '/services/userService') but its not working any ideas how to i need to reference this?
Thanks.
I think you are creating a new module instead of use yours.
To retrieve an existing module and use it in a separated file, you have to do :
var app = angular.module('app')
.service('user', userService')
// ...
Instead of
var app = angular.module('app', ['ngRoute'])
.service('user', userService')
// ...
Documentation available at https://docs.angularjs.org/guide/module#creation-versus-retrieval
EDIT from #koox00 answer
Don't forgot to load all files related to your module in your markup, in the good order (before load the file containing your module declaration).

Dependencies Between Modules - Controllers?

This tells AngularJS that all values, factories and services defined inside the myUtilModule should be available inside the myOtherModule module too. In other words, myOtherModule depends on myUtilModule.
var myUtilModule = angular.module("myUtilModule", []);
myUtilModule.value ("myValue" , "12345");
var myOtherModule = angular.module("myOtherModule", ['myUtilModule']);
myOtherModule.controller("MyController", function($scope, myValue) {
});
My question is: What if you define controllers inside myUtilModule and try to use them on myOtherModule. Is this possible?
Yes, controllers will also be available between modules, a pratical example could be as follows:
angular.module('test.controllers').controller('HomeCtrl');
and then on your main module:
angular.module('test', [
'test.controllers',
'test.services',
...
];
This helps a lot on unit testing and reusability of packages.

Include Angular into Hackathon-Starter

I'm quite a newbie. I try to include Angular into the https://github.com/sahat/hackathon-starter Boilerplate. I included
//= require lib/ui-bootstrap-tpls-0.11.0
//= require lib/angular
into the application.js and the two files into the lib folder.
Still, the app does not seem to work on Angular yet. What do I do wrong? Where do I put my code for controllers/directives etc.?
Using Hackathon-starter-angular (HSA) doesn't answer questions which were mentioned in the post. HSA includes AngularJS globally in the layout.jade file which might mean that all routes are served by AngularJS and those pages are not indexed by search engines like google.
Another solution to include/inject AngularJS into hackathon-starter is to do it locally. Here are steps how to do it:
1) Create a controller which will delegate to angularjs all requests on a particular route. Place the controller inside e.g. angularEntry.js
exports.getPagesServedByAngular = function (req, res) {
res.render('shop/index', {
title: 'Entry point to AngularJS pages'
});
};
2) Require the controller inside app.js
// reference the controller
var angularPagesController = require('./controllers/angular');
// use it
app.get('/shop', angularPagesController.getPagesServedByAngular);
3) Create a new folder inside views (e.g. shop) and create the new file inside it with the name (e.g. index.jade). This file will serve as an entry point for Angular application. Paste inside the file the following code:
extends ../layout
block content
.page-header
h3 Services
body(data-ng-app='miniApp')
p first test expression from views/index.jade: {{ 5 + 5 }}
div(data-ng-view)
4) Create app.js inside public/js for the mini application. For test purpases I just put inside it:
angular.module('miniApp', ['ngRoute']);
angular.module('miniApp').config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/test.html'
})
.when('/detailTest', {
templateUrl: 'views/detailTest.html'
})
});
5) Download libraries like angular.js and angular-route.js inside public/js/lib folder
6) Add references to them in public/js/application.js as following:
//= require lib/angular
//= require lib/angular-route
//= require app
7) Create test pages like test.html and detailTest.html inside public/views folder
At this point, Angular should be integrated. So, put your client-side controllers/directives inside public/js folder.
Someone make a fork that includes angular into hackathon-starter: https://github.com/squeezeday/hackathon-starter-angular

Resources