-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyLocations.js
342 lines (311 loc) · 14.8 KB
/
myLocations.js
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
'use strict';
angular.module('myApp', ['ui.router', 'uiGmapgoogle-maps', 'LocalStorageModule', 'isteven-multi-select'])
// definition of states & views
.config(['$stateProvider', function ($stateProvider) {
// thin wrapper for storage resolve promise
var asPromise = function ($q, func) {
var deferred = $q.defer();
var value = func();
if (value)
deferred.resolve(value);
else
deferred.reject("object not found in storage");
return deferred.promise;
};
// define application states
$stateProvider
// welcome screen
.state('root', {
url: '',
views: {
'top': { templateUrl: 'templates/top.html', controller: function ($scope) {
// a click on toolbar will generate event that should be handled by main controllers
$scope.actionClick = function (action) {
$scope.$root.$broadcast(action.event, action);
}
} },
'main': { templateUrl: 'templates/home.html' },
'bottom': { templateUrl: 'templates/bottom.html' }
},
data: { toolbarLabel: "myLocations" }
})
// category list screen (supports "new" action from toolbar)
.state('root.category', {
url: '/category',
views: { 'main@': { templateUrl: 'templates/categoryList.html', controller: 'myApp.ctrl.categoryList' } },
data: {
toolbarLabel: "Category List",
toolbarActions: [
{ event: "toolbarNew", label: "New" }
]
}
})
// new category screen
.state('root.category.new', {
url: '/new',
views: { 'main@': { templateUrl: 'templates/categoryEdit.html', controller: 'myApp.ctrl.categoryEdit' } },
resolve: { category: function () {
return null;
} },
data: {
toolbarLabel: "New Category",
toolbarActions: [
{ event: "toolbarSave", label: "Save" }
]
}
})
// edit category screen (will edit only existing entities)
.state('root.category.edit', {
url: '/:id',
views: { 'main@': { templateUrl: 'templates/categoryEdit.html', controller: 'myApp.ctrl.categoryEdit' } },
resolve: {
category: ['$q', '$stateParams', 'myApp.storage', function ($q, $stateParams, storage) {
return asPromise($q, function () {
return storage.getCategory($stateParams.id);
});
}]
},
data: {
toolbarLabel: "Category Edit",
toolbarActions: [
{ event: "toolbarSave", label: "Save" },
{ event: "toolbarDelete", label: "Delete" }
]
}
})
// location list screen (supports "new" action from toolbar)
.state('root.location', {
url: '/location',
views: { 'main@': { templateUrl: 'templates/locationList.html', controller: 'myApp.ctrl.locationList' } },
data: {
categorized: false,
toolbarLabel: "Location List",
toolbarActions: [
{ event: "toolbarNew", label: "New" },
{ event: "toolbarCategorized", label: "Categorize View" }
]
}
})
// new location screen
.state('root.location.new', {
url: '/new',
views: { 'main@': { templateUrl: 'templates/locationEdit.html', controller: 'myApp.ctrl.locationEdit' } },
resolve: { location: function () {
return null;
} },
data: {
toolbarLabel: "New Location",
toolbarActions: [
{ event: "toolbarSave", label: "Save" }
]
}
})
// edit location screen (will edit only existing entities)
.state('root.location.edit', {
url: '/:id',
views: { 'main@': { templateUrl: 'templates/locationEdit.html', controller: 'myApp.ctrl.locationEdit' } },
resolve: {
location: ['$q', '$stateParams', 'myApp.storage', function ($q, $stateParams, storage) {
return asPromise($q, function () {
return storage.getLocation($stateParams.id);
});
}]
},
data: {
toolbarLabel: "Location Edit",
toolbarActions: [
{ event: "toolbarSave", label: "Save" },
{ event: "toolbarDelete", label: "Delete" }
]
}
});
}])
// init google maps
// see here for details: http://angular-ui.github.io/angular-google-maps/#!/use
.config(['uiGmapGoogleMapApiProvider', function(GoogleMapApi) {
GoogleMapApi.configure({ v: '3.20', libraries: '' });
}])
// application initialization code
.run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) {
// attach ui-router state & params to global root scope
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
// for debugging
//$rootScope.$on("$stateChangeError", console.log.bind(console));
}])
// local storage service
// we store categories and locations as objects in local storage.
// each item in these objects has id property as a key, and location or category object as a value.
// this allows us to refer category and location by number instead of by name.
.service('myApp.storage', ['localStorageService', function ($storage) {
// register storage values with defaults (only for demonstration effect)
if (!$storage.get('categories') || !$storage.get('locations')) {
$storage.set('categories', {
"0": {id: 0, name: "Bars"},
"1": {id: 1, name: "Shops"},
"2": {id: 2, name: "Restaurants"},
"next": 3
});
$storage.set('locations', {
"0": {id: 0, name: "The Lool", address: "Herzl St 202, Rehovot", categories: [0], coords: { latitude: 31.899396805165384, longitude: 34.81049190953979 } },
"1": {id: 1, name: "Crocs Shoes", address: "Jabotinski St 45, Ashdod", categories: [1], coords: { latitude: 31.8105665, longitude: 34.6529708 } },
"2": {id: 2, name: "Moo & Moo", address: "Herzl St 177, Rehovot", categories: [2], coords: { latitude: 31.898473441968346, longitude: 34.81029882488406 } },
"next": 3
});
}
// will return the named list of entities
this.getList = function (listName) {
var list = $storage.get(listName);
delete list.next;
return list;
};
// will return a specific entity
this.getEntity = function (listName, id) {
return $storage.get(listName)[id];
};
// delete an entity
this.removeEntity = function (listName, id) {
var list = $storage.get(listName);
delete list[id];
$storage.set(listName, list);
};
// will add/replace entity, update its id as necessary
this.persistEntity = function (listName, entity) {
var list = $storage.get(listName);
if (typeof(entity.id) !== 'number')
entity.id = list.next++;
list[entity.id] = entity;
$storage.set(listName, list);
};
// create shortcuts for categories and locations
this.getCategories = this.getList.bind(this, 'categories');
this.getCategory = this.getEntity.bind(this, 'categories');
this.removeCategory = this.removeEntity.bind(this, 'categories');
this.persistCategory = this.persistEntity.bind(this, 'categories');
this.getLocations = this.getList.bind(this, 'locations');
this.getLocation = this.getEntity.bind(this, 'locations');
this.removeLocation = this.removeEntity.bind(this, 'locations');
this.persistLocation = this.persistEntity.bind(this, 'locations');
// helper function - convert storage list to sorted array by name
this.asSortedArray = function (list) {
return Object.keys(list).map(function (id) {
return list[id];
}).sort(function (c1, c2) {
return c1.name > c2.name ? 1 : -1;
});
};
}])
// controller for the categories list view
.controller('myApp.ctrl.categoryList', ['$scope', 'myApp.storage', function ($scope, storage) {
// populate scope
$scope.categories = storage.asSortedArray(storage.getCategories());
// define new action
$scope.$on("toolbarNew", function () {
$scope.$state.go(".new");
});
}])
// controller for add/edit category (category is null for "new" state)
.controller('myApp.ctrl.categoryEdit', ['$scope', 'myApp.storage', 'category', function ($scope, storage, category) {
// define validation function (returns true on success, and also updates $scope.validation
// with detailed error status)
var validate = function () {
$scope.validation = {};
if (!$scope.category.name)
$scope.validation.name = 'Name parameter is required';
return Object.keys($scope.validation).length === 0;
};
// populate scope
if (category) {
$scope.category = category; // edit category
$scope.locationsFiltered = storage.asSortedArray(storage.getLocations()).filter(function(location){
return location.categories.indexOf(category.id) != -1;
});
$scope.$on("toolbarDelete", function () {
if ($scope.locationsFiltered.length == 0) {
storage.removeCategory($scope.category.id);
$scope.$state.go("^");
} else
$scope.validation = { delete: "Can't delete category with assigned locations" };
});
} else {
$scope.category = {}; // new category (start with empty fields)
$scope.locationsFiltered = [];
}
// define save action
$scope.$on("toolbarSave", function () {
if (validate()) {
storage.persistCategory($scope.category);
$scope.$state.go("^"); // back to list
}
});
}])
// controller for the locations list view
.controller('myApp.ctrl.locationList', ['$scope', 'myApp.storage', function ($scope, storage) {
// populate scope
var plainCategories = storage.getCategories();
$scope.categories = storage.asSortedArray(plainCategories);
$scope.categories.forEach(function(category) {
// prepare empty locations array for every category value
category.locations = [];
});
$scope.locations = storage.asSortedArray(storage.getLocations());
$scope.locations.forEach(function(location) {
location.categories.forEach(function(categoryId) {
plainCategories[categoryId].locations.push(location);
})
});
$scope.categorized = $scope.$state.$current.data.categorized;
// define new & categorize actions
$scope.$on("toolbarNew", function () {
$scope.$state.go(".new");
});
$scope.$on("toolbarCategorized", function (event, action) {
$scope.$state.$current.data.categorized = !$scope.$state.$current.data.categorized;
action.label = $scope.$state.$current.data.categorized ? "Flatten View" : "Categorize View";
$scope.categorized = $scope.$state.$current.data.categorized;
});
}])
// controller for add/edit location (location is null for "new" state)
.controller('myApp.ctrl.locationEdit', ['$scope', 'myApp.storage', 'location', function ($scope, storage, location) {
// define validation function (returns true on success, and also updates $scope.validation
// with detailed error status)
var validate = function () {
$scope.validation = {};
if (!$scope.location.name)
$scope.validation.name = 'Name parameter is required';
if (!$scope.location.address)
$scope.validation.address = 'Address parameter is required';
if ($scope.categoriesSelectOutput.length == 0)
$scope.validation.categories = 'At least one category is required';
return Object.keys($scope.validation).length === 0;
};
// populate scope
$scope.categories = storage.getCategories();
if (location) {
$scope.location = location; // edit location
$scope.$on("toolbarDelete", function () {
storage.removeLocation($scope.location.id);
$scope.$state.go("^");
})
} else
// new location (start with empty fields, default map at Azrieli Center)
$scope.location = { coords: { latitude: 32.074392875096414, longitude: 34.79195251522219 } };
$scope.categoriesSelectInput = storage.asSortedArray($scope.categories).map(function (category) {
// mark selected categories in the input-model of the "isteven-multi-select" component
// see description here: http://isteven.github.io/angular-multi-select/#/configs-options
category.ticked = $scope.location.categories && ($scope.location.categories.indexOf(category.id) != -1);
return category;
});
$scope.localLang = { nothingSelected: "Select at least one category" };
$scope.mapCenter = _.clone($scope.location.coords); // do not mix map center and location coordinates
// define save action
$scope.$on("toolbarSave", function () {
if (validate()) {
$scope.location.categories = $scope.categoriesSelectOutput.map(function (category) {
return category.id;
});
storage.persistLocation($scope.location);
$scope.$state.go("^"); // back to list
}
});
}]);