Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

AngularJS1.5に再挑戦 その5 URL Routing Part 1

概要

AngularJS1.5に再挑戦 その5 URL Routing Part 1

参考動画・参考サイト

Coding for Entrepreneurs

AngularJS — Superheroic JavaScript MVW Framework

URL Routing Part 1

  • ngRouteを利用してみる。

AngularJS

  • $ rackup で開発用サーバ立ち上げておく。

  • 公式サイトの、ngRouteのCDN用URLを読み込む。"//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.js"の箇所。XYZのところを自分が使っているバージョンを入れる。

...
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.js'></script>
...
  • 上記urlをコピペする際に、httpsをつけておくと尚良しとのこと。

  • さらに、//ajax.googleapis.com/ajax/libs/angularjs/X.Y.Z/angular-route.jsの最後のファイル名部分をangular-resource.jsに変えたurlも読み込んでおく。

...
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-resource.js'></script>
...
  • rackupの開発サーバで利用する際にはrelative pathではなく、absolute pathに変更しておく。
        <script src='/js/app/app.module.js'></script>
        <script src='/js/app/app.config.js'></script>

        <script src='/js/app/blog-list/blog-list.module.js' ></script>
        <script src='/js/app/blog-list/blog-list.component.js' ></script>
  • app.module.jsに、ngRouteと、ngResourceを追記しておく。
'use strict';

angular.module('try', [
    // external
    'ngResource',
    'ngRoute',

    // internal
    'blogList'
]);
  • app.config.jsにコードを追記する。
'use strict';

angular.module('try').
    config(
        function(
            $locationProvider,
            $routeProvider
            ){

            $routeProvider.
                when("/blog/1",{
                    template: "<h1>Hi<h1>"
                }).
                when("/blog/2",{
                    template: "<blog-list></blog-list>"
                }).
                otherwise({
                    template: "Not Found"
                })
    });
  • これで、index.htmlにアクセスしてみる。。。routeによる表示の変更が反映されていない。。。index.htmlを以下のように修正してみる。これについては後で調べておこう。
    <body>
        <div ng-view>
    </div>
    </body>
  • うーん、ng-viewが機能しないな。。。まあ後回しにしよう。

  • 最終的に、以下のようにapp.config.jsを修正した。

'use strict';

angular.module('try').
    config(
        function(
            $locationProvider,
            $routeProvider
            ){
            $locationProvider.html5Mode({
                enabled:true
                })

            $routeProvider.
                when("/", {
                    template: "<blog-list></blog-list>"
                }).
                when("/blog/1", {
                    template: "<h1>Hi<h1>"
                }).
                when("/blog/2", {
                    template: "<blog-list></blog-list>"
                }).
                otherwise({
                    template: "Not Found"
                })
    });

URL Routing Part 2

  • app.config.jsに、/about ルートを追記する。
'use strict';

angular.module('try').
    config(
        function(
            $locationProvider,
            $routeProvider
            ){
            $locationProvider.html5Mode({
                enabled:true
                })

            $routeProvider.
                when("/", {
                    template: "<blog-list></blog-list>"
                }).
                when("/about",{
                    template: "/templates/about.html"
                }).
                when("/blog/1", {
                    template: "<h1>Hi<h1>"
                }).
                when("/blog/2", {
                    template: "<blog-list></blog-list>"
                }).
                otherwise({
                    template: "Not Found"
                })

    });
  • templates/about.htmlを追加作成する。
<h1>About Us</h1>

<p>
    about ページです。
</p>
  • index.htmlにコードを追記する。
    <body>
        <h1>Us</h1>
        <blog-list></blog-list>
        <div ng-view>

        </div>
    </body>
  • 相変わらず<div ng-view></div>は機能せず。。。

URL Routing Part 3 - RouteParams

  • app.config.jsに、idを渡す
'use strict';

angular.module('try').
    config(
        function(
            $locationProvider,
            $routeProvider
            ){
            $locationProvider.html5Mode({
                enabled:true
                })

            $routeProvider.
                when("/", {
                    template: "<blog-list></blog-list>"
                }).
                when("/about",{
                    template: "/templates/about.html"
                }).
                when("/blog/:id", {
                    template: "<blog-list></blog-list>"
                }).
                // when("/blog/2", {
                //     template: "<blog-list></blog-list>"
                // }).
                otherwise({
                    template: "Not Found"
                })

    });
  • blog-list.component.jsを修正する。$routeParamsを表示させるようにする。routeParamsは、多分、djangoでいうところのurls.pyの、url内にあるとか、に当たる箇所だと思う。routeからparameterを取得できる。ここでは、idを取得するようにしている。
'use strict';

angular.module('blogList').
    component('blogList', {
        templateUrl: '/templates/blog-list.html',
        controller: function($routeParams, $scope){
            console.log($routeParams.id)

            var blogItems = [
                {title: "Some Title", id:1, description: "This is a book", publishDate: "2017-01-08"},
                {title: "Title2", id:2, description: "This is a book"},
                {title: "Some Title3", id:3, description: "This is a book"},
                {title: "Some Title4", id:4, description: "This is a book"},
            ]

            $scope.items = blogItems;

            $scope.title = 'Hi there!'
            $scope.clicks = 0
            $scope.someClickTest = function(){
            console.log("clicked")
            $scope.clicks += 1
            $scope.title = 'Clicked ' + $scope.clicks + '回'
            }
        }
    });
  • 上記の例の場合は、idの部分が、routeParamsが渡される。

  • 例えば、以下のようにapp.config.jsに追記するとする。

                when("/blog/:id", {
                    template: "<blog-list></blog-list>"
                }).
                when("/blog/:id/:abc", {
                    template: "<blog-list></blog-list>"
  • こちらの例の場合は、それぞれ以下のようにconsoleに表示される。
// http://127.0.0.1:9292/blog/1/にアクセスした時は以下のようにconsoleに表示される。
Object { id: "1" }

// http://127.0.0.1:9292/blog/1/ddddの場合は

Object { id: "1", abc: "dddd" }blog-list.component.js:7:13

// http://127.0.0.1:9292/blog/1/ccccの場合は

Object { id: "1", abc: "cccc" }blog-list.component.js:7:13
  • やはりかなりdjangoのurl routeに似ているという印象がする。

AngularJS1.5に再挑戦 その5 Local Webserver for AngularJS and Javascript Apps

概要

AngularJS1.5に再挑戦 その5 URL Routing Part 1

参考動画・参考サイト

Coding for Entrepreneurs

AngularJS — Superheroic JavaScript MVW Framework

Local Webserver for AngularJS and Javascript Apps

  • 以下の動画で、local webserverを立ち上げる必要があるらしい。ruby のgemのrackを使うとのこと。

www.youtube.com

  • git hubの参照用ページはこちら。

Guides/angular_webserver.md at master · codingforentrepreneurs/Guides · GitHub

  • 色々必要なものをinstallする。
$ sudo gem install bundler
  • Gemfileというファイルを作成して、そこに以下のように、記述する。
source 'https://rubygems.org'
gem 'rack'
  • bundle installする。
$ bundle install
  • ここでerror発生!rack-2.0.1 requires ruby version >= 2.2.2, which is incompatible with the current version, ruby 2.0.0p648とのこと。なので、rubyを新しいものに変える。

  • rubyを以下の手順で変えてみる。

$ brew install ruby-build
$ brew install rbenv
$ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> .bash_profile
$ echo 'eval "$(rbenv init -)"' >> .bash_profile
$ source .bash_profile
$ rbenv install 2.2.3
$ rbenv global 2.2.3
  • 再度、$ bundle install。。。。あーこれでもダメだな。どうもbundlerのrubyのversionが古いのかなぁ。。。とりあえず、bundlerを再度今のversionのrubyで、installしておく。あとsudoを外してinstallする。
$ gem install bundler
$ bundle install
  • できた〜〜!続いて、config.ru というファイルを作成し、以下のコードをコピペする。
use Rack::Static,
  :urls => ["/images", "/js", "/css", "/templates"],
  :root => "src"

run lambda { |env|
  [
    200,
    {
      'Content-Type'  => 'text/html',
      'Cache-Control' => 'public, max-age=86400'
    },
    File.open('src/index.html', File::RDONLY)
  ]
}
  • $ rackup をターミナルで実行する。。。うまくいったぽいので、http://localhost:9292/にアクセスする。(多分ポートは毎回変わるのか?)

  • よし、とりあえず、できた。

AngularJS1.5に再挑戦 その4 External Templates & Looping in a Template with ng-repeat

概要

AngularJS1.5に再挑戦 その4 External Templates

参考動画・参考サイト

Coding for Entrepreneurs

AngularJS — Superheroic JavaScript MVW Framework

External Templates

  • blog-list.component.jsを修正する。templateUrlという便利そうな機能を使ってみる。
'use strict';

angular.module('blogList').
    component('blogList', {
        templateUrl: '/templates/blog-list.html',
        controller: function($scope){
            $scope.title = 'Hi there!'
            $scope.clicks = 0
            $scope.someClickTest = function(){
            console.log("clicked")
            $scope.clicks += 1
            $scope.title = 'Clicked ' + $scope.clicks + '回'
            }
        }
    });
  • templatesフォルダを作成し、その中に、blog-list.htmlを作成する。
<div class=''>
    <h1 class='new-class'>{{ title }}</h1>
    <button ng-click='someClickTest()'>Click me!</button>
</div>
  • これで、components blogListが、blog-list.htmlをtemplateとして、<blog-list></blog-list>に出力するようになる。これはdjangoにかなり近い使用感覚なので覚えやすい。

Looping in a Template with ng-repeat

  • blog-list.components.jsにコードを追記する。function内でしか使わない変数は、varで定義する。
'use strict';

angular.module('blogList').
    component('blogList', {
        templateUrl: '/templates/blog-list.html',
        controller: function($scope){
            var blogItems = [
                {title: "Some Title", id:1, description: "This is a book"},
                {title: "Title2", id:2, description: "This is a book"},
                {title: "Some Title3", id:3, description: "This is a book"},
                {title: "Some Title4", id:4, description: "This is a book"},
            ]

            $scope.items = blogItems;

            $scope.title = 'Hi there!'
            $scope.clicks = 0
            $scope.someClickTest = function(){
            console.log("clicked")
            $scope.clicks += 1
            $scope.title = 'Clicked ' + $scope.clicks + '回'
            }
        }
    });
  • ng-repeatを利用して、繰り返し表示処理をしてみる。ng-repeatは、for文のようなイメージで使える。
<div class=''>
    <h1 class='new-class'>{{ title }}</h1>
    <button ng-click='someClickTest()'>Click me!</button>
</div>

{{ items }}

<ul>
    <li ng-repeat='item in items'>{{ item.title }}</li>
</ul>
  • さらに以下のように修正すると、itemごとのリンクも取得できる。(今はまだ設定してないけど)
<ul>
    <li ng-repeat='item in items'><a href='/blog/{{ item.id }}'>{{ item.title }}</li>
</ul>
  • ng-hrefに変えておく。ng-hrefは微妙に動作が違うらしい。今は、わからない。<li ng-repeat='item in items'><a ng-href='/blog/{{ item.id }}'>{{ item.title }}</li>

  • ng-ifを利用して、アイテムのリストの数によって、表示の方法を変更する。

<h1>Blog List</h1>
<ul ng-if='items.length > 0'>
    <li ng-repeat='item in items'><a ng-href='/blog/{{ item.id }}'>{{ item.title }} {{ item.publishDate }}</li>
</ul>

<span ng-if='items.length == 0'>Posts coming soon</span>
  • かなりdjangoに似ていることがわかってきた。

AngularJS1.5に再挑戦 その3 Create the Angular App & A Controller & Component

概要

AngularJS1.5に再挑戦 その3 Create the Angular App

参考動画・参考サイト

Coding for Entrepreneurs

AngularJS — Superheroic JavaScript MVW Framework

Create the Angular App

  • js/appフォルダを作成する。

  • js/appフォルダに、app.module.js, app.config.jsを追加する。

'use strict';

angular.module('try', []);
  • tryというのが、moduleの名前かな。ng-app='try'とかで指定できる。

  • app.module.jsは、angularのappの機能を書く。app.config.jsは、その機能を拡張するためのconfigurationをするためのもの。

  • そして、それぞれindex.htmlに読み込ませる必要がある。

        <script src='./js/app/app.module.js'></script>
        <script src='./js/app/app.config.js'></script>

A Controller & Component

  • app/blog-listというフォルダを作成する。

  • blog-list.component.js, blog-list.module.jsを作成する。

  • blog-list.module.jsは以下の通り。

'use strict';

angular.module('bloglist', []);
  • blog-list.component.jsは以下の通り。controllerというのを作成してみる。
'use strict';

angular.module('bloglist').
    controller('BlogListController', function(){
        console.log("hello")
    });
    // component('bloglist');
  • index.htmlに読み込ませる。
...
        <script src='./js/app/blog-list/blog-list.module.js' ></script>
        <script src='./js/app/blog-list/blog-list.component.js' ></script>
...
    <body>
...
        <div class='' ng-controller='BlogListController'>

        </div>
...
  • さらにapp.module.jsに, moduleを読み込ませる。
'use strict';

angular.module('try', ['blogList']);
  • ページにアクセスして、consoleに、helloと表示されていればOK。

  • blog-list.component.jsに、$scopeを追記してみる。scopeは、contextと似ているところがあって、引き継ぎが可能。

'use strict';

angular.module('blogList').
    controller('BlogListController', function($scope){
        console.log("hello")
        $scope.title = 'Hi there!'
    });
    // component('bloglist');
  • さらにindex.htmlにコードを追記する。
...
        <div class='' ng-controller='BlogListController'>
            {{ title }}
        </div>
...
  • これで、BlogListControllerからcontextされた、titleを表示できる。

  • さらに部分を以下のように修正する。buttonのsomeClickTestというfunctionを、BlogListControllerに書き込む必要がある。

    <body>
        <div class='' ng-controller='BlogListController'>
            <h1 class='new-class'>{{ title }}</h1>
            <button ng-click='someClickTest'>Click me!</button>
        </div>
    </body>
  • BlogListControllerに、someClickTestを定義する。動作は、clickすると、consoleに、clickedと表示されて、$scope.titleを、Clickedに上書きするもの。
'use strict';

angular.module('blogList').
    controller('BlogListController', function($scope){
        console.log("hello")
        $scope.title = 'Hi there!'
        $scope.someClickTest = function(){
            console.log("clicked")
            $scope.title = 'Clicked'
        }
    });
    // component('bloglist');
  • これで、表示されるはず。。。あら、なぜか反映されない。。。あー、よく見たら、ng-click='someClickTest'ではなくて、ng-click='someClickTest()'が正解だ。修正したら無事反映。functionの時は、引数が必要だということか。

  • clickの回数を数えて、表示させる機能をつける。context変数は、js内では、$scope.で指定して、html内では、{{}}で表示するとざっくり覚えておこう。

'use strict';

angular.module('blogList').
    controller('BlogListController', function($scope){
        console.log("hello")
        $scope.title = 'Hi there!'
        $scope.clicks = 0
        $scope.someClickTest = function(){
            console.log("clicked")
            $scope.clicks += 1
            $scope.title = 'Clicked ' + $scope.clicks + '回'
        }
    });
    // component('bloglist');
  • component機能を使ってみる。
'use strict';

angular.module('blogList').
    component('blogList', {
        template: "<div class=''><h1 class='new-class'>{{ title }}</h1><button ng-click='someClickTest()'>Click me!</button></div>",
        controller: function($scope){
            $scope.title = 'Hi there!'
            $scope.clicks = 0
            $scope.someClickTest = function(){
            console.log("clicked")
            $scope.clicks += 1
            $scope.title = 'Clicked ' + $scope.clicks + '回'
        }
    });
  • 注意点は、ng-controller='BlogListController'は、削除する。

  • `<blog-list></blog-list>は、component名のblogListを、htmlのtag用に変換したものになる。そのため、component名が、blogListViewとかだと、<blog-list-view>で囲むことになる。

AngularJS1.5に再挑戦 その2 Link Angular from Local & CDN と Binding & Conditionals

概要

AngularJS1.5に再挑戦 その2 Link Angular from Local & CDN

参考動画・参考サイト

Coding for Entrepreneurs

AngularJS — Superheroic JavaScript MVW Framework

Link Angular from Local & CDN

  • angular.min.jsをscriptとして読み込まれるようにindex.htmlにコードを追記する。
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Try Angular 1.5</title>
        <script src='./js/angular.min.js'></script>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>
  • src=の箇所は、angular公式のhttps://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.jsに変更することもできる。そしてたぶんそちらの方が推奨されてるぽい。

Initialize Angular

  • index.htmlを以下のように修正してみる。
<!DOCTYPE html>
<html lang="ja" ng-app> #ng-appがangularのapplicationだと認識させるタグ? 
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Try Angular 1.5</title>
        <!-- <script src='./js/angular.min.js'></script> -->
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js'></script>
    </head>
    <body>
        <h1>Hello, {{ name }}!</h1>
        <input type='text' ng-model='name' /># nag-modelをnameと変数
    </body>
</html>
  • すげー簡単!djangoと似てるな。

Binding & Conditionals

  • ng-if を使ってみる。ng-if='name'は、nameというangular変数?が空でなければという意味だと思われる。逆は、ng-if='!name'。
<h1>Hello, <span ng-if='name'>{{ name }}</span><span ng-if='!name'>World</span>!</h1>
  • ng-classを使ってみる。ng-classは条件を指定して、その条件に当てはまる時に、指定したclassを適応することができる。
        <style>
        .new-class{
            font-size: 72px;

        }
        .other-class{
            font-size: 32px;
        }
        </style>

    </head>
    <body>
        <h1 class='new-class' ng-class="{'other-class': name}">Hello,
            <span ng-if='name'>{{ name }}</span>
            <span ng-if='!name'>World</span>
            !
        </h1>
        <input type='text' ng-model='name' />
  • ここでは、h1 のclassは、もともと new-classだが、ng-classを指定することで、nameがある場合に関しては、other-classを適応することができる。

  • またもっと細かい条件を指定することも可能。以下は、nameがjunkoの時だけ、classをchangeする。

h1 class='new-class' ng-class="{'other-class': name=='junko'}">Hello,
            <span ng-if='name'>{{ name }}</span>
            <span ng-if='!name'>World</span>
            !
        </h1>
  • fontサイズもng変数に変更可能.
        <style>
        .new-class{
            font-size: 72px;

        }
        .other-class{
            font-size: {{ font }};
        }
        </style>

    </head>
    <body>
        <h1 class='new-class' ng-class="{'other-class': name=='junko'}">Hello,
            <span ng-if='name'>{{ name }}</span>
            <span ng-if='!name'>World</span>
            !
        </h1>
        <input type='text' ng-model='name' />

        <input type='text' ng-model='font' placeholder="fontsize">
    </body>
  • さらにng-classは、いくつか組み合わせ可能。
        <style>
        .new-class{
            font-size: 72px;

        }
        .other-class{
            font-size: 32px;
        }
        .new-class2{
            font-size: 120px;
        }
        </style>

    </head>
    <body>
        <h1 class='new-class' ng-class="{'other-class': name=='junko', 'new-class2': font==120}">Hello,
            <span ng-if='name'>{{ name }}</span>
            <span ng-if='!name'>World</span>
            !
        </h1>
        <input type='text' ng-model='name' />

        <input type='text' ng-model='font' placeholder="fontsize">
    </body>
  • これは綺麗にまとまりそうやなぁ。

AngularJS1に再挑戦 その1 Download AngularJS

概要

AngularJS1.5に再挑戦 その1 Download AngularJS

参考動画・参考サイト

Coding for Entrepreneurs

AngularJS — Superheroic JavaScript MVW Framework

Before we get started

  • angularJS1をゲットする。(現時点で、最新バージョンが1.6になっとる。)angular.min.js をダウンロードする。

  • tryangular/JS/angular.min.jsという形でファイルを配置する。

  • index.htmlファイルを作成する。内容は以下の通り。

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Try Angular 1.5</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>
  • srcというフォルダを作成して、js, index.htmlをそこに入れる。

  • $ python -m http.serverで、ローカル開発サーバーを起動させることができる。python2の場合は、$ python -m SimpleHTTPServerらしい。

  • quicktips.mdというファイルを作っておき、そこにコマンドを記録しておく。後から参照できるようにと、共有用にかな。

  • http://0.0.0.0:8000/にアクセスすると、hello worldが表示されればOK!

Githubでbranchを作成して、pull requestする方法

概要

今さならながら、githubのチーム開発に着手(^ ^;) 今回は、pull requestまでをやってみた。 forkからではなく、自分も編集できるリモートリポジトリを対象としている。

Github branchを作成->pull request

  • ここでは、README.mdファイルを編集してpull requestしている。
$ git add README.md
$ git commit -m "README.mdにinstall手順を追記しました"
$ git checkout -b readme_branch
# ここでbranchを切って、新しいbranchを作成する。
$ git push origin readme_branch
  • githubにアクセスして、readme_branchのCompare&pull requestをクリックする。これで完了!

  • 意外と、シンプルに終わるな(^ ^)ただ、forkしてからのpull requestはもうちょっとややこしそうやな。。。怖い。