forked from Apress/pro-angularjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducts.js
More file actions
90 lines (74 loc) · 2.47 KB
/
products.js
File metadata and controls
90 lines (74 loc) · 2.47 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
angular.module("exampleApp", ["increment", "ngResource", "ngRoute", "ngAnimate"])
.constant("baseUrl", "http://localhost:5500/products/")
.factory("productsResource", function ($resource, baseUrl) {
return $resource(baseUrl + ":id", { id: "@id" },
{ create: { method: "POST" }, save: { method: "PUT" } });
})
.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when("/edit/:id", {
templateUrl: "/editorView.html",
controller: "editCtrl"
});
$routeProvider.when("/create", {
templateUrl: "/editorView.html",
controller: "editCtrl"
});
$routeProvider.otherwise({
templateUrl: "/tableView.html",
controller: "tableCtrl",
resolve: {
data: function (productsResource) {
return productsResource.query();
}
}
});
})
.controller("defaultCtrl", function ($scope, $location, productsResource) {
$scope.data = {};
$scope.createProduct = function (product) {
new productsResource(product).$create().then(function (newProduct) {
$scope.data.products.push(newProduct);
$location.path("/list");
});
}
$scope.deleteProduct = function (product) {
product.$delete().then(function () {
$scope.data.products.splice($scope.data.products.indexOf(product), 1);
});
$location.path("/list");
}
})
.controller("tableCtrl", function ($scope, $location, $route, data) {
$scope.data.products = data;
$scope.refreshProducts = function () {
$route.reload();
}
})
.controller("editCtrl", function ($scope, $routeParams, $location) {
$scope.currentProduct = null;
if ($location.path().indexOf("/edit/") == 0) {
var id = $routeParams["id"];
for (var i = 0; i < $scope.data.products.length; i++) {
if ($scope.data.products[i].id == id) {
$scope.currentProduct = $scope.data.products[i];
break;
}
}
}
$scope.cancelEdit = function () {
$location.path("/list");
}
$scope.updateProduct = function (product) {
product.$save();
$location.path("/list");
}
$scope.saveEdit = function (product) {
if (angular.isDefined(product.id)) {
$scope.updateProduct(product);
} else {
$scope.createProduct(product);
}
$scope.currentProduct = {};
}
});