FrAngular services
by tchatel
HTML
<div ng-app="app" ng-controller="Ctrl">
<h2>{{title}}</h2>
<ul>
<li ng-repeat='year in yearsWithLabel'>{{year}}</li>
</ul>
<div>Release : {{release}} - Author : {{author}}</div>
</div>
CSS
h2 {
font-size: 1.4em;
font-weight: bold;
}
ul {
margin: 1em;
}
JavaScript
var app = angular.module('app', ['services']);
app.config(['Author', 'LabelServiceProvider', function(Author, LabelServiceProvider) {
Author.init('Thierry Chatel');
LabelServiceProvider.init('Year');
}]);
app.controller('Ctrl', ['$scope', 'Info', 'Release', 'Author', 'LabelService', function ($scope, Info, Release, Author, LabelService) {
$scope.title = Info.title;
$scope.release = Release;
$scope.author = Author.get();
$scope.yearsWithLabel = LabelService.getYearsWithLabel();
}]);
var services = angular.module('services', []);
services.value('Info', {
title: 'Services Demo',
version: '1.0',
dataSize: 10
});
services.value('AppUtils', {
trim: function (text) {
return typeof text == 'string' ? text.replace(/^\s*/, '').replace(/\s*$/, '') : text;
},
endsWith: function (text, suffix) {
return text.indexOf(suffix, text.length - suffix.length) !== -1;
}
});
services.factory('Release', ['Info', 'AppUtils', function (Info, AppUtils) {
var release = Info.version
+ (AppUtils.endsWith(Info.version, '.0')
? ' (major release)'
: ' (minor release)');
return release;
}]);
function Data(Info) {
this.years = [];
for (var i = 0 ; i < Info.dataSize ; i++) {
this.years.push(2013 - i);
}
}
Data.prototype.getYears = function () {
return this.years;
};
services.service('Data', ['Info', Data]);
services.provider('LabelService', function () {
var label;
this.init = function (txt) {
label = txt;
};
// Service factory method, with dependancy injection
this.$get = ['Data', function (Data) {
var yearsWithLabel = [];
angular.forEach(Data.getYears(), function (value, key) {
yearsWithLabel.push(label + ' ' + value);
});
// Returns the service object
return {
getYearsWithLabel: function (value) {
return...