Skip to content

Instantly share code, notes, and snippets.

@hgwood
Created February 10, 2015 13:14
Show Gist options
  • Save hgwood/2f9f11e7eff1f144d675 to your computer and use it in GitHub Desktop.
Save hgwood/2f9f11e7eff1f144d675 to your computer and use it in GitHub Desktop.
Example of integrating CommonJS with Angular's DI without writing modules
require("angular");
module.exports = angular;
"use strict";
module.exports = function AppController(appService) {
this.greetings = appService.greetings;
};
"use strict";
module.exports = function appService() {
this.greetings = "hello world";
};
"use strict";
var diverge = require("./diverge");
diverge("app", [
require("./app-controller"),
require("./app-service"),
]);
"use strict";
var angular = require("angularjs");
module.exports = function diverge(rootModuleName, commonjsModules) {
var ngModules = commonjsModules.map(function (commonjsModule) {
var ngComponent = getNgNameAndType(commonjsModule.name);
var ngModule = angular.module(commonjsModule.name, []);
ngModule[ngComponent.type](ngComponent.name, commonjsModule);
return ngModule.name;
});
angular.module(rootModuleName, ngModules);
};
function getNgNameAndType(exportedFunctionName) {
var match = exportedFunctionName.match(/(.*)(Controller|Service|Factory|Filter|Directive)$/);
return {name: match[0], type: match[2].toLowerCase()};
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<title></title>
<script src="bundle.js"></script>
</head>
<body ng-controller="AppController as app">
{{::app.greetings}}
</body>
</html>
{
"name": "diverge",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "browserify app.js -o bundle.js",
"serve": "npm run build && python -m SimpleHTTPServer 8001"
},
"author": "",
"license": "ISC",
"devDependencies": {
"browserify": "^8.1.3",
"browserify-shim": "^3.8.2"
},
"dependencies": {
"angular": "~1.3.12",
"lodash": "^3.1.0"
},
"browserify-shim": {
"angular": "global:angular"
},
"browser": {
"angularjs": "./angular.browserify.js"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment