Skip to content

Instantly share code, notes, and snippets.

@ritch
Last active August 29, 2015 14:24
Show Gist options
  • Save ritch/3bc26ab330294cb12fc1 to your computer and use it in GitHub Desktop.
Save ritch/3bc26ab330294cb12fc1 to your computer and use it in GitHub Desktop.
Idea to simplify the definition of angular modules

Idea: Simpler Angular Modules

Its easy to mess up angular module definitions. What if there was a simpler way to define them? It would prevent typo errors such as forgetting to update both references in the injects array.

Instead of trying to change the runtime... why not just generate what angular (1 and 2) wants with a new simple syntax.

Gulp

My proposed implementation is a gulp plugin that does the following.

gulp.task('js', function() {
  return gulp.src('modules/*.js')
    .pipe(simpleAngularModules())
    .pipe(gulp.dest('dist'));
});

Hello World

Typical angular hello world:

angular.
module('myModule', []).
 controller('MyController', ['$scope', function ($scope) {
   $scope.hello = function() {
     alert('hello world');
   }
 }]);

Using the proposed syntax this would be rewritten as:

/**
* @module MyModule
* @controller MyController
* @inject $scope
*/

$scope.hello = function() {
 alert('hello world');
}

A couple things to note. The content of the simplified versions file would be run in a self calling function / scope. This means there aren't global variables.

For controllers, the contents of the file is the "exported" function. For directives, you must specify functions by name to be set as properties on the returned directive definition (eg. link, templateUrl).

/**
* @module myServiceModule
* @controller MyController
* @inject $scope notify
*/
$scope.callNotify = function(msg) {
notify(msg);
};
/**
* @module myServiceModule
* @factory notify
*/
var msgs = [];
function notify(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
}
// typical angular style
angular.
module('myServiceModule', []).
controller('MyController', ['$scope','notify', function ($scope, notify) {
$scope.callNotify = function(msg) {
notify(msg);
};
}]).
factory('notify', ['$window', function(win) {
var msgs = [];
return function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment