11.09.2014

Membuat CRUD Sederhana Dengan Node.js, MongoDB, Express dan AngularJS Part 2


Persiapan

Pastikan anda sudah mengikuti 2 tutorial dibawah ini:

  1. Membuat Hello World Dengan Node.js dan Express
  2. Membuat CRUD Sederhana Dengan Node.js, MongoDB, Express dan AngularJS Part 1
atau anda bisa download project terakhir yang sudah diupload di github.

Jika anda sudah mengikuti 2 tutorial diatas atau download project di github, pastikan struktur file dan folder-nya seperti ini:

--crud-api-nodejs-express-mongodb ---- models ------ car.js ---- node_modules ---- routes  ------ car.js ---- app.js ---- package.json

Catatan:
Rename nama folder "crud-api-nodejs-express-mongodb" menjadi "crud-nodejs-express-mongodb-angular". Ubah juga atribut "name" pada file package.json menjadi sama dengan nama folder yang baru.


Let's make some cakes!

Setelah kita berhasil membuat API untuk fungsi CRUD, sekarang kita akan membuat satu halaman untuk menampilkan data yang ada di database.

Sebelumnya masukan beberapa data melalui aplikasi Postman sebagai data awal.


...

Buatlah folder baru di root bernama "public", kemudian simpan file didalamnya dan berinama index.html. Masukan kode ini didalam file yang baru dibuat:

Hello world from file!

Lalu buka file app.js, ganti router nya yang asalnya

res.send("Hello world!");

menjadi

res.sendfile('./public/index.html');

Kemudian akses http://localhost:8080/ pada browser...



Kita sudah berhasil routing menggunakan file index.html.

Setting Up Angular

Buatlah file core.js didalam folder public, lalu pasang kode berikut didalamnya:

// public/core.js
var carsManager = angular.module('carsManager', []);

function mainController($scope, $http) {
    $scope.formData = {};

    // when landing on the page, get all cars and show them
    $http.get('/car/')
        .success(function(data) {
            $scope.cars = data;
            console.log(data);
        })
        .error(function(data) {
            console.log('Error: ' + data);
        });

    // when submitting the add form, send the text to the node API
    $scope.createCar = function() {
        $http.post('/car/', $scope.formData)
            .success(function(data) {
                // clear the form so our user is ready to enter another
                     $scope.formData = {}; 
   
  $http.get('/car/')
   .success(function(data) {
    $scope.cars = data;
    console.log(data);
   })
   .error(function(data) {
    console.log('Error: ' + data);
   });
    
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    // delete a car after checking it
    $scope.deleteCar = function(id) {
        $http.delete('/car/' + id)
            .success(function(data) {    
  $http.get('/car/')
   .success(function(data) {
    $scope.cars = data;
    console.log(data);
   })
   .error(function(data) {
    console.log('Error: ' + data);
   });
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };

    // update a car
    $scope.updateCar = function() {
        $http.put('/car/' + $scope.formDataUpdate.id, $scope.formDataUpdate)
            .success(function(data) {
                // clear the form so our user is ready to enter another                                
                $scope.formDataUpdate = {}; 
    
  $http.get('/car/')
   .success(function(data) {
    $scope.cars = data;
    console.log(data);
   })
   .error(function(data) {
    console.log('Error: ' + data);
   });
    
            })
            .error(function(data) {
                console.log('Error: ' + data);
            });
    };
}

Disana kita membuat sebuah module (carsManager) dan sebuah controller (mainController).

Frontend View

Lalu pasang kode html pada file index.html untuk menampilkan data yang sudah diambil.

<!-- index.html --> <!doctype html> <!-- ASSIGN OUR ANGULAR MODULE --> <html ng-app="carsManager"> <head> <!-- META --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport --> <title>Simple Cars Management</title> <!-- SCROLLS --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"><!-- load bootstrap --> <style> html { overflow-y:scroll; } body { padding-top:50px; } #todo-list { margin-bottom:30px; } </style> <!-- SPELLS --> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script><!-- load jquery --> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script><!-- load angular --> <script src="core.js"></script> </head> <!-- SET THE CONTROLLER AND GET ALL TODOS --> <body ng-controller="mainController"> <div class="container"> <!-- HEADER AND TODO COUNT --> <div class="jumbotron text-center"> <h1>Cars Management <span class="label label-info">{{ cars.length }}</span></h1> </div> <!-- CAR LIST --> <div id="car-list" class="row"> <div class="form-group"> <h2>Create form</h2> <!-- FORM TO CREATE CAR --> <form> <table class="table table-striped" width="90%"> <colgroup> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="*" /> </colgroup> <tr> <td> <input type="text" placeHolder="Model" class="form-control text-center" width="100%" ng-model="formData.model"/> </td> <td> <input type="text" placeHolder="Year" class="form-control text-center" width="100%"ng-model="formData.year"/> </td> <td> <input type="text" placeHolder="Color" class="form-control text-center" width="100%"ng-model="formData.color"/> </td> <td> <input type="text" placeHolder="Price" class="form-control text-center" width="100%"ng-model="formData.price"/> </td> <td> <input type="submit" class="btn btn-primary" value="Add" ng-click="createCar()" width="100%"/> </td> </tr> </table> </form> <h2>Update form</h2> <!-- FORM TO UPDATE CAR --> <form> <table class="table table-striped" width="90%"> <colgroup> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="*" /> </colgroup> <tr> <td> <select id="carId" placeHolder="Model" class="form-control text-center" ng-model="formDataUpdate.id" required> <option ng-repeat="car in cars" value="{{car._id}}"> {{car.model}} </option> </select> </td> <td> <input type="text" placeHolder="Year" class="form-control text-center" width="100%"ng-model="formDataUpdate.year"/> </td> <td> <input type="text" placeHolder="Color" class="form-control text-center" width="100%"ng-model="formDataUpdate.color"/> </td> <td> <input type="text" placeHolder="Price" class="form-control text-center" width="100%"ng-model="formDataUpdate.price"/> </td> <td> <input type="submit" class="btn btn-primary" value="Update" ng-click="updateCar()" width="100%"/> </td> </tr> </table> </form> </div> <h2>Data</h2> <!-- LOOP OVER THE CAR IN $scope.cars --> <table class="table table-striped" width="90%"> <colgroup> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="15%" /> <col width="*" /> </colgroup> <tr> <th> Model </th> <th> Year </th> <th> Color </th> <th> Price </th> <th> Action </th> </tr> <tr ng-repeat="car in cars"> <td> {{ car.model }} </td> <td> {{ car.year }} </td> <td> {{ car.color }} </td> <td> {{ car.price }} </td> <td> <input type="submit" class="btn btn-warning" value="Delete" ng-click="deleteCar(car._id)"/> </td> </tr> </table> </div> </div> </body> </html>

Sekarang coba buka http://localhost:8080 , maka tampilannya akan seperti ini:



Code at github

Jika mengalami kesulitan mengikuti tutorial ini atau punya beberapa pertanyaan, bisa tulis di bagian komentar atau download contoh kode nya disini.

Semoga bermanfaat, terima kasih.

5 comments:

  1. gan pas pake postman

    {
    "model":"APV",
    "year":"2010",
    "color":"Red",
    "price":"2000"
    }

    muncul eror, kaya gini, kenapa ya?

    {
    "error": {
    "message": "Validation failed",
    "name": "ValidationError",
    "errors": {
    "model": {
    "message": "Validator failed for path `model` with value ``",
    "name": "ValidatorError",
    "path": "model",
    "type": "user defined"
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. coba periksa gan di controllernya, mungkin ada yang salah nulis, intinya dia ngira si model itu null... atau coba download contoh source nya, trus bandingin ... :)

      Delete
  2. Trims Buat Tutorial nya...

    Wait for next tutorial.... :D

    ReplyDelete
  3. gan, itu nama databasenya apa, dan nama collection nya apa?

    ReplyDelete
    Replies
    1. Ada di halaman sebelumnya gan -> http://www.blog.asepmaulanaismail.com/2014/11/membuat-api-crud-sederhana-dengan-node-js-mongodb-express.html?m=1

      Delete