How to re-use code between AngularJS client and Node.js server [closed] How to re-use code between AngularJS client and Node.js server [closed] express express

How to re-use code between AngularJS client and Node.js server [closed]


Using angular in non-browser environment

Ben Clinkinbeard prepared angular distribution as a commonJS module (HERE), that can run in a non-browser environment:

AngularJS compiled with jsdom and provided as a CommonJS module. Intended for testing AngularJS code without depending on a browser.


If you want to be more cherry-picking you probably should wait for angular 2.0

Sharing code between client-side and server-side

And again... Ben Clinkinbeard. In THIS TALK he describes how to make use of browserify in an angular project. One cool feature of this approach is that you can declare your functions/objects as separate entities that are not coupled with angular anyhow; so they can be re-used in different contexts as well.

An example of it:

app.js

var app = angular.module('someModule',[]);...app.factory('someService', require('./some/path.js'));...

./some/path.js

module.exports = function(dep1, dep2){  ...  return {     ...  }}module.exports.$inject['dep1', 'dep2']; // for minification;


Angular 1.x is pretty self contained framework. There is a plan to break functionalities apart, but that will come in version 2. So this would be simple as just provide different implementation of $httpBackend for browser and node.js.

I have created a simple demo how to share code between node.js and browser with CommonJS. This can be used for sharing validation, models etc.


Using RequireJS for this make sense here.

Instead of defining your model/service inside of Angular like this:

(function (angular) {  "use strict";  angular.module('myModule').factory('MyModel', function (Deps) {    var Model = function () {      // do things here    };    return Model;  });}(window.angular));

You would do it this way splitting it in 2 files:

model.js:

(function (define) {  "use strict";  define([], function () {    var factoryConstructor = function (deps) {      var Model = function () {        // do things here      };      return Model;    };    return factoryConstructor;  });}(window.define));

whatever.js

(function (define, angular) {  "use strict";  define(['Model'], function (Model) {    angular.module("myModule").factory("myModel", Model);  });}(window.define, window.angular));

Check this Videos for a good example on how to implement this, there is also the repository from that video.