あいつの日誌β

働きながら旅しています。

Angular and Sails.JS in 10 mins documentation

This documentation is copied from youtube video

this is from here.

https://www.youtube.com/watch?v=Cpo0jDYltO0

create backend app

% cd ~
% mkdir web && cd $_
% sails new backend
% cd backend
% sails generate food

allow CORS on all routes. edit: backend/config/cors.js

-       allRoutes: false,
+       allRoutes: true,

start.

% sails lift

backend has already been created. check http://localhost:13370/food

create frontend app

% cd ~/web
% mkdir frontend && cd $_

All answer is default yes.

% yo angular web

create food action.

% yo angular:route food
% grunt serve

check http://localhost:9000/#/food

if anything errors happen, try to these commands and grunt serve again.

% npm cache clean && npm install
% bower cache clean && bower install

edit Angular.js code

edit: frontend/app/scripts/controllers/food.js

'use strict';

angular.module('webApp')
    .controller('FoodCtrl', function($scope, $resource) {

        var Food = $resource('http://localhost:1337/food', {
            id: '@id'
        }, {
            update: {
                method: 'PUT'
            }   
        }); 

        $scope.food = new Food();
        $scope.foodList = Food.query();

        $scope.saveFood = function() {

            var method = $scope.food.id ? '$update' : '$save';

            $scope.food[method]({}, function() {

                $scope.food = new Food();
                $scope.foodList = Food.query();

                console.log("Saved!!");
            })
        };

        $scope.editFood = function(food) {
            $scope.food = food;
        };


    });

edit: frontend/app/views/food.html

<div class="row">

    <form action="" ng-submit="saveFood()" method="POST" role="form">
        
        <legend>New Food</legend>

        <div class="form-group">
            <label for="">Food Name</label>
            <input type="text" ng-model="food.name" class="form-control" id="" placeholder="Input field" />
        </div>

        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    
    <h1>My Food List!!</h1>

    <ul>
        <li ng-repeat="food in foodList">
            {{ food.name }}
            <button ng-click="editFood(food)">Edit</button>
        </li>
    </ul>

</div>

open

% open http://127.0.0.1:9000/#/food

Enjoy:)