Browse Source

Levels 3.1 to 3.3.: defining and consuming a Factory service.

Frederic G. MARAND 6 years ago
parent
commit
8329fd3111

+ 5 - 0
index.html

@@ -48,6 +48,11 @@
 
     <script src="./js/app.js"></script>
     <script src="./js/routes.js"></script>
+
+    <!-- Services -->
+    <script src="./js/services/note.js"></script>
+
+    <!-- Controllers -->
     <script src="./js/controllers/notes-create-controller.js"></script>
     <script src="./js/controllers/notes-edit-controller.js"></script>
     <script src="./js/controllers/notes-index-controller.js"></script>

+ 6 - 0
js/controllers/notes-edit-controller.js

@@ -0,0 +1,6 @@
+angular.module('noteWrangler')
+  .controller("NotesEditController", ['$scope', 'Note', function ($scope, Note) {
+    $scope.updateNote = function (noteObj) {
+      Note.create(noteObj);
+    };
+  }]);

+ 4 - 6
js/controllers/notes-index-controller.js

@@ -1,5 +1,5 @@
 angular.module("noteWrangler")
-  .controller("NotesIndexController", function ($http, $scope) {
+  .controller("NotesIndexController", ['$scope', 'Note', function ($scope, Note) {
     const errorHandler = function (err) {
       console.log("Error getting /notes", err);
     };
@@ -8,8 +8,6 @@ angular.module("noteWrangler")
       $scope.notes = data.data;
     };
 
-    $http({
-      method: "GET",
-      url: "/notes.json"
-    }).then(responseHandler, errorHandler);
-  });
+    Note.all()
+      .then(responseHandler, errorHandler);
+  }]);

+ 34 - 0
js/services/note.js

@@ -0,0 +1,34 @@
+/*
+There are 5 types of services:
+
+* Most popular:
+  * Factory: used to share functions and objects across an app.
+  * Provider: like factory, but with configuration
+* Others:
+  * Constant
+  * Service
+  * Value
+
+ */
+
+
+angular.module("noteWrangler")
+  // Naming the function <service>Factory is a common convention.
+  .factory('Note', ['$http', function NoteFactory($http) {
+    return {
+      all: function () {
+        return $http({
+          method: "GET",
+          url: "/notes.json",
+        });
+      },
+
+      create: function (note) {
+        return $http({
+          method: "PUT",
+          url: "/notes",
+          data: note,
+        });
+      },
+    }
+  }]);