aboutsummaryrefslogtreecommitdiffstats
path: root/app/assets/javascripts/services/notes.js
blob: 87b618b05d61b3cb6f7ecee33a19b7e7a02a86e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
(function(angular) {
	angular
		.module('nt.NotesService', [
			'ngResource'
		])
		.service('NotesService', [
			'$resource',
			function($resource) {
				var Note = $resource('/notes/:id.json',
					{ id: '@id' },
					{
						update: {
							method: 'PUT'
						}
					}
				);

				this.notes = null;
				this.current_note = null;

				this.fetch = function() {
					this.notes = Note.query();

					return this.notes.$promise;
				};

				this.open = function(note) {
					this.current_note = note;
				};

				this.update = function() {
					this.current_note.$update();
				};

				this.create = function(note_title) {
					if (note_title) {
						Note.save({
							title: note_title,
							body: ''
						},
						(response) => {
							delete this.new_note_title;
							this.show_create = false;
							this.fetch().then(() => {
								this.current_note = this.notes.find((el) => {
									return el.id === response.id;
								});
							});
						});
					}
				};

				this.delete = function(note) {
					this.notes.splice(this.notes.indexOf(note), 1);
					note.$delete().then(() => {
						this.current_note = null;
					});
				};
			}
		]);
})(window.angular);