mkdir -p src/sample-app/clock
AngularJS modules are defined by placing a module.json
file in your module (sub-)directory. This file is mandatory for your module to be recognized, but can be as small as an empty object ({}
) if your module doesn't need fancy settings. Let's create a dummy module.json
file in the src/sample-app/clock/
directory:
src/sample-app/clock/module.json
{}
This will define a module named sampleApp.clock
. Notice that the directory structure produces a corresponding module: path separators (/
or \
) are replaced by dots (.
), and kebab-case in directory names (sample-app
) is replaced by camelCase (sampleApp
).
Now that our module is defined, let's get started by creating a simple view:
src/sample-app/clock/display.template.html
<div sample-app-clock-widget></div>
Time to define the sampleAppClockWidget
directive:
src/sample-app/clock/widget.directive.js
function($interval) {
return {
restrict: 'A',
templateUrl: 'sample-app/clock/widget.template.html',
scope: {},
link: function postlink(scope) {
$interval(function updateTime() {
scope.time = new Date();
}, 1000);
}
};
}
src/sample-app/clock/widget.template.html
<span class="clock-widget" ng-bind="time | date : 'mediumTime'"></span>
The entry point of the styles definitions lies in module.scss
.
src/sample-app/clock/module.scss
.clock-widget {
background-color: #2c3e50;
border-radius: .5em;
border: 1px solid #34495e;
color: #c0392b;
display: inline-block;
font: bold 2em sans-serif;
padding: .5em 1em;
}
Run gulp ng-build
. This will create a dist/js/sampleApp.clock.js
file, which should be similar to:
dist/js/sampleApp.clock.js
(function() {
'use strict';
angular
.module("sampleApp.clock", [])
.run(function($templateCache) {
/* templates injections */
})
.directive("sampleAppClockWidget", function widget($interval) {
/* directive definition */
})
;
})();
You should notice a few things:
- your templates (
*.template.html
) are injected directly into the template cache to reduce the number of HTTP requests necessary to load the application; - your directive function has been named (
function($interval) { /* ... */ }
becamefunction widget($interval) { /* ... */ }
); - your directive name has been prefixed (
widget.directive.js
produces thesampleAppClockWidget
directive).
The index file was also generated by the process, and should import the dist/js/sampleApp.clock.js
and the dist/css/sampleApp.clock.css
files:
dist/index.html
<!doctype html>
<html ng-app="sampleApp" ng-strict-di>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/sampleApp.clock.css">
<script src="/js/sampleApp.clock.js"></script>
</head>
<body></body>
</html>