ch05-03-simple-angular-service.js
3.08 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// ch05-03-simple-angular-service.js
// this example shows three different ways of defining our own "service"...
// use 'factory()' for functions/plain objects API
// use 'service()' for JS class object API
// use 'provider()' for configurable service API
// this is a service definition
function ItemServiceTwo() {
var items = [
{id: 0, label: 'Item 0'},
{id: 1, label: 'Item 1'}
];
this.list = function () {
return items;
};
this.add = function (item) {
items.push(item);
};
}
// this is a provider definition
function ItemServiceThree(optItems) {
var items = optItems || [];
this.list = function () {
return items;
};
this.add = function (item) {
items.push(item);
}
}
angular.module('notesApp', [])
// [provider] define item service as configurable provider
.provider('ItemServiceThree', function () {
var haveDefaultItems = true;
this.disableDefaultItems = function () {
haveDefaultItems = false;
};
// this function gets our dependencies..
this.$get = [function () {
var optItems = [];
if (haveDefaultItems) {
optItems = [
{id: 0, label: 'Item 0'},
{id: 1, label: 'Item 1'}
];
}
return new ItemServiceThree(optItems);
}];
})
// [provider] define configuration for provider
.config(['ItemServiceThreeProvider', function (ItemServiceThreeProvider) {
// to see how the provider can change configuration
// change the value of shouldHaveDefaults to true and
// try running the example
var shouldHaveDefaults = false;
// get configuration from server.
// set shouldHaveDefaults somehow
// assume it magically changes for now
if (!shouldHaveDefaults) {
ItemServiceThreeProvider.disableDefaultItems();
}
}])
// [service] define item service as a JS class
.service('ItemServiceTwo', [ItemServiceTwo])
// [factory] define item service factory
.factory('ItemService', [function () {
var items = [
{id: 0, label: 'Item 0'},
{id: 1, label: 'Item 1'}
];
return {
list: function () {
return items;
},
add: function (item) {
items.push(item);
}
};
}])
// ======================================================================
// define controllers...
.controller('MainCtrl', [function () {
var self = this;
self.tab = 'first';
self.open = function (tab) {
self.tab = tab;
};
}])
.controller('SubCtrl', ['ItemService', function (ItemService) {
var self = this;
self.list = function () {
return ItemService.list();
};
self.add = function () {
var n = self.list().length;
ItemService.add({
id: n,
label: 'Item ' + n
});
};
}]);