Include Angular into Hackathon-Starter - angularjs

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

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).

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).

Best practices to inject custom module in meanjs

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

Loading relative templateUrl

I've been trying to find the best way to create a modular, scalable angular application. I really like the structure of projects like angular-boilerplate, angular-app, where all the related files are grouped together by feature for partials and directives.
project
|-- partial
| |-- partial.js
| |-- partial.html
| |-- partial.css
| |-- partial.spec.js
However, in all these examples, the template URL is loaded relative to the base url, not relative to the current file:
angular.module('account', [])
.config(function($stateProvider) {
$stateProvider.state('account', {
url: '/account',
templateUrl: 'main/account/account.tpl.html', // this is not very modular
controller: 'AccountCtrl',
});
})
This is not very modular, and could become difficult to maintain in large projects. I would need to remember to change the templateUrl path every time I moved any of these modules. It would be nice if there was some way to load the template relative to the current file like:
templateUrl: './account.tpl.html'
Is there any way to do something like this in angular?
The best way to do this now is using a module loader like browserify, webpack, or typescript. There are plenty of others as well. Since requires can be made from the relative location of the file, and the added bonus of being able to import templates via transforms or loaders like partialify, you don't even have to use template urls anymore. Just simply inline the Template via a require.
My old answered is still available below:
I wrote a post on exactly this subject and spoke on it at our local Angular Meetup. Most of us are now using it in production.
It is quite simple as long as your file structure is represented effectively in your modules. Here is a quick preview of the solution. Full article link follows.
var module = angular.module('myApp.things', []);
var all = angular.module('myApp.things.all', [
'myApp.things',
'things.someThing',
'things.someOtherThing',
'things.someOtherOtherThing',
]);
module.paths = {
root: '/path/to/this/thing/',
partials: '/path/to/this/thing/partials/',
sub: '/path/to/this/thing/sub/',
};
module.constant('THINGS_ROOT', module.paths.root);
module.constant('THINGS_PARTIALS', module.paths.partials);
module.constant('THINGS_SUB', module.paths.sub);
module.config(function(stateHelperProvider, THINGS_PARTIALS) {
stateHelperProvider.setNestedState({
name: 'things',
url: '/things',
templateUrl: THINGS_PARTIALS + 'things.html',
});
});
And then any sub modules or "relative" modules look like this:
var module = angular.module('things.someThing', ['myApp.things']);
var parent = angular.module('myApp.things');
module.paths = {
root: parent.paths.sub + '/someThing/',
sub: parent.paths.sub + '/someThing/sub/',
partials: parent.paths.sub + '/someThing/module/partials/',
};
module.constant('SOMETHING_ROOT', module.paths.root);
module.constant('SOMETHING_PARTIALS', module.paths.partials);
module.constant('SOMETHING_SUB', module.paths.sub);
module.config(function(stateHelperProvider, SOMETHING_PARTIALS) {
stateHelperProvider.setNestedState({
name: 'things.someThing',
url: "/someThing",
templateUrl: SOMETHING_PARTIALS + 'someThing.html',
});
});
Hope this helps!
Full Article: Relative AngularJS Modules
Cheers!
I think you'll eventually find that maintaining the paths relative to the js file will be harder, if even possible. When it comes time to ship, you are most likely going to want to concatenate all of your javascript files to one file, in which case you are going to want the templates to be relative to the baseUrl. Also, if you are fetching the templates via ajax, which Angular does by default unless you pre-package them in the $templateCache, you are definitely going to want them relative to the baseUrl, so the server knows where to find them once your js file has already been sent to the browser.
Perhaps the reason that you don't like having them relative to the baseUrl in development is because you aren't running a server locally? If that's the case, I would change that. It will make your life much easier, especially if you are going to work with routes. I would check out Grunt, it has a very simple server that you can run locally to mimic a production setup called Grunt Connect. You could also checkout a project like Yeoman, which provides a pre-packaged front end development environment using Grunt, so you don't have to spend a lot of time getting setup. The Angular Seed project is a good example of a Grunt setup for local development as well.
I've been chewing on this issue for a while now. I use gulp to package up my templates for production, but I was struggling to find a solution that I was happy with for development.
This is where I ended up. The snippet below allows any url to be rewired as you see fit.
angular.module('rm').config(function($httpProvider) {
//this map can be defined however you like
//one option is to loop through script tags and create it automatically
var templateMap = {
"relative.tpl.html":"/full/path/to/relative.tpl.html",
etc...
};
//register an http interceptor to transform your template urls
$httpProvider.interceptors.push(function () {
return {
'request': function (config) {
var url = config.url;
config.url = templateMap[url] || url;
return config;
}
};
});
});
Currenly it is possible to do what you want using systemJs modules loader.
import usersTemplate from './users.tpl';
var directive = {
templateUrl: usersTemplate.name
}
You can check good example here https://github.com/swimlane-contrib/angular1-systemjs-seed
I had been using templateUrl: './templateFile.tpl.html but updated something and it broke. So I threw this in there.
I've been using this in my Gruntfile.js html2js object:
html2js: {
/**
* These are the templates from `src/app`.
*/
app: {
options: {
base: '<%= conf.app %>',
rename: function( templateName ) {
return templateName.substr( templateName.lastIndexOf('/') );
}
},
src: [ '<%= conf.app %>/**/{,*/}<%= conf.templatePattern %>' ],
dest: '.tmp/templates/templates-app.js'
}
}
I know this can lead to conflicts, but that is a smaller problem to me than having to edit /path/to/modules/widgets/wigdetName/widgetTemplate.tpl.html in every file, every time, I include it in another project.

How is modularity mitigated in AngularJS?

I've been playing with the seed app for AngularJS and I noticed that most dependencies (controllers, directive, filters, services) for the app are loaded up front. I was wondering how to modularize an Angular app into smaller bytes, where dependencies aren't loaded unless required.
For example, if I had a large application that had a cart, add/edit shipping address, search results, product details, product lists, etc... A user on a shopping site may never encounter any of these views, but it looks like (from the seed app) that the code for these all views are loaded in at startup.
How is modularity mitigated in AngularJS?
This question about modularity is being asked quite often here on SO and the google group. I'm not part of core team but my understanding is the following one:
You can easily load partials (HTML/templates fragments) on demand by including them (ngInclude) or referencing them in directives / routes. So at least you don't need to download all the partials up-front (although you might want to do so, see the other question here: Is there a way to make AngularJS load partials in the beginning and not at when needed?)
When it comes to JavaScript (controller, directives, filters etc. - basically everything that is defined in AngularJs modules) I believe that there is no, as of today, support for on-demand load of modules in AngularJS. This issue closed by the core team is an evidence of this: https://github.com/angular/angular.js/issues/1382
Lack of the on-demand load of AngularJS modules might sound like a big limitation, but:
when it comes to performance one can't be sure till things are measured; so I would suggest simply measuring if this is a real problem for you
usually code written with AngularJS is really small, I mean, really small. This small code base minified and gzipped might result in a really small artifact to download
Now, since this question is coming back so often I'm sure that the AngularJS team is aware of this. In fact I saw some experimental commits recently ( https://github.com/mhevery/angular.js/commit/1d674d5bfc47d18dc4a14ee0feffe4d1f77ea23b#L0R396 ) suggesting that the support might be in progress (or at least there are some experiments with it).
I've been playing lately with require modules and angular and I've implemented lazy loading of partials and controllers.
It can be easily done without any modifications to Angular sources (version 1.0.2).
Repository: https://github.com/matys84pl/angularjs-requirejs-lazy-controllers .
There is also an implementation that uses yepnope (https://github.com/cmelion/angular-yepnope) made by Charles Fulnecky.
All we need is put this code in our application config, as that:
application.config [
"$provide", "$compileProvider", "$controllerProvider", "$routeProvider"
, ($provide, $compileProvider, $controllerProvider, $routeProvider) ->
application.controller = $controllerProvider.register
application.provider = $provide.provider
application.service = $provide.service
application.factory = $provide.factory
application.constant = $provide.constant
application.value = $provide.value
application.directive = -> $compileProvider.directive.apply application, arguments
_when = $routeProvider.when
$routeProvider.when = (path, route) ->
loaded = off
route.resolve = new Object unless route.resolve
route.resolve[route.controller] = [
"$q",
($q) ->
return loaded if loaded
defer = $q.defer()
require [
route.controllerUrl
], (requiredController) ->
defer.resolve()
loaded = on
defer.promise
]
_when.call $routeProvider, path, route
For use add require our components in modules where we need ( provider, constant, directive etc ). Like that:
define [
"application"
"services/someService"
], (
application
) ->
application.controller "chartController", [
"$scope", "chart", "someService"
, ($scope, chart, someService) ->
$scope.title = chart.data.title
$scope.message = chart.data.message
]
someService.coffee file:
define [
"application"
], (
application
) ->
application.service "someService", ->
#name = "Vlad"
And add to controllerUrl our path to controller for routing:
application.config [
"$routeProvider"
, ($routeProvider) ->
$routeProvider
.when "/table",
templateUrl: "views/table.html"
controller: "tableController"
controllerUrl: "controllers/tableController"
resolve:
table: ($http) ->
$http
type: "GET"
url: "app/data/table.json"
]
tableController.coffee file:
define [
"application"
"services/someService"
], (
application
) ->
application.controller "tableController", [
"$scope", "table"
, ($scope, table) ->
$scope.title = table.data.title
$scope.users = table.data.users
]
And all components have "lazy" load in place where our need.

Resources