Skip to content

Commit ba23021

Browse files
feat($time): create time service
Add simple $time service to allow easier mocking dates in applications. Closes angular#10402
1 parent f3b088a commit ba23021

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-0
lines changed

angularFiles.js

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ var angularFiles = {
3737
'src/ng/sniffer.js',
3838
'src/ng/templateRequest.js',
3939
'src/ng/testability.js',
40+
'src/ng/date.js',
4041
'src/ng/timeout.js',
4142
'src/ng/urlUtils.js',
4243
'src/ng/window.js',

src/AngularPublic.js

+2
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
$TemplateCacheProvider,
8181
$TemplateRequestProvider,
8282
$$TestabilityProvider,
83+
$TimeProvider,
8384
$TimeoutProvider,
8485
$$RAFProvider,
8586
$$AsyncCallbackProvider,
@@ -234,6 +235,7 @@ function publishExternalAPI(angular) {
234235
$templateCache: $TemplateCacheProvider,
235236
$templateRequest: $TemplateRequestProvider,
236237
$$testability: $$TestabilityProvider,
238+
$date: $DateProvider,
237239
$timeout: $TimeoutProvider,
238240
$window: $WindowProvider,
239241
$$rAF: $$RAFProvider,

src/ng/date.js

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'use strict';
2+
3+
/**
4+
* @ngdoc service
5+
* @name $date
6+
* @requires $window
7+
*
8+
* @description
9+
* Simple service for accessing date.
10+
*
11+
* The main purpose of this service is to simplify mocking date in tests.
12+
*
13+
* @example
14+
<example module="dateExample">
15+
<file name="script.js">
16+
angular.module('dateExample', [])
17+
.controller('TimeController', ['$scope', '$date', function($scope, $date) {
18+
$scope.now = $date.now();
19+
}]);
20+
</file>
21+
<file name="index.html">
22+
<div ng-controller="TimeController">
23+
<p>Time when the page was created: {{now | date}}</p>
24+
</div>
25+
</file>
26+
</example>
27+
*/
28+
function $DateProvider() {
29+
var self = this;
30+
31+
this.$get = ['$window', function($window) {
32+
return {
33+
/**
34+
* @ngdoc method
35+
* @name $date#now
36+
*
37+
* @description
38+
* Return Date object representing current date
39+
*/
40+
now: function () {
41+
return $window.Date();
42+
}
43+
};
44+
}];
45+
}

test/ng/dateSpec.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/* global $TimeProvider: false */
2+
'use strict';
3+
4+
describe('$date', function() {
5+
var $window;
6+
7+
beforeEach(module(function($provide) {
8+
$window = {};
9+
10+
$provide.value('$window', $window);
11+
}));
12+
13+
it('should return Date.new() when $date.now() is called', inject(
14+
function() {
15+
$window.Date = function() {
16+
return Date(1418998923940);
17+
};
18+
},
19+
function($date) {
20+
var date = $date.now();
21+
expect(date).toEqual(Date(1418998923940));
22+
}
23+
));
24+
25+
});

0 commit comments

Comments
 (0)