2015年5月19日

3.2 組織網頁應用產品(Webapp)

  • Yeoman介紹
    我們建議使用Yeoman來發展你的網頁應用產品,他整合很多JS前端的技術,例如BootstrapCompassModernizrCoffeeScriptJasminePhantomJSGrunt等。

  • Yeoman軟體開發流程
    在軟體開發流程階段可以分為需求訪談、產品分析、產品開發、產品測試和上線,這些步驟Yeoman有提供完整前端開發工具與架構。在官方網站可以看到下圖Yeoman前端開發流程架構圖,從產品開發到上線,Yeoman 首先利用yo工具快速開發網頁的骨架、當會載入不同JS框架時可以應用bower框架之間相依性,最後產品上線前會經過壓縮、測試、打包 package 等佈署動作這些可以使用grunt完成。

    yeoman

    Yeoman包含三套工具
    (1) yo      : 當建構新的應用系統,可以用來建立新的建構環境
    (2) bower : 套件管理用來管理JS框架之間的相依關係
    (3) grunt  :  部屬前檔案壓縮、預覽、測試webapp專案

  • Yeoman環境安裝
    為了可以安裝Yeoman的架構,我們必須先安裝node.js , Git for WindowsRubyInstaller 這三套工具,
    才可以安裝Yeoman的工具,

    Step1. 下載node.js,安裝node.js: https://nodejs.org/download/
    注意: 需要安裝python 2.6或是python 2.7
    nodejs

    確定是否安裝成功
    image

    Step2. 下載git安裝,git : https://git-scm.com/

    git

    確定git安裝成功
    image

    Step3. 下載ruby安裝 :http://rubyinstaller.org/downloads/
    image

    安裝時,注意的事項
    ruby

    image

 

  • Yeoman安裝
    步驟一、確定node.js版本與npm的版本
    在命令列輸入:

    node --version && npm --version
    v0.12.3
    2.9.1


    步驟二: 安裝yo bower和 grunt套件
    C:\Users\bryan\npm> npm install --global yo bower grunt-cli
    …安裝明細

    C:\Users\bryan\npm>node --version && npm --version
    v0.12.3
    2.9.1


    步驟三: 安裝產生器
    (1) 安裝webapp產生器
    C:\Users\bryan\npm> npm install -g generator-webapp

    (2) 安裝angular產生器
    C:\Users\bryan\npm> npm install -g generator-angular






3.1前言


我們接下來介紹使用AngularJS開發產品時,使用哪些工具或是方法會讓開發流程更有效率且符合軟體開發流程使用。

  1. 如何規畫網頁應用程式開發用於快速應用程式開發模式
  2. 使用Karma工具用於單元測試
  3. 產品佈署時,將AngularJS編碼編譯為最小化
  4. 使用Batarang來偵錯(debug)
  5. 簡化開發流程
  6. 整合RequireJS來管理版本JS函式庫相依性





2015年5月18日

AngularJS - 教學


1. 介紹AngularJS套件
1.1  AngularJS介紹
1.2  MVC
1.3  Template And Data Binding
1.4  Dependency Injection
1.5  Directive & Filter

2.AngularJS深入淺出
2.1 第一個AngularJS程式
2.2 List、Tables and Other Repeated Elements
2.3 過濾器
2.4 路由與多視圖
2.5

3.AngularJS前端開發
3.1 前言
3.2 組織網頁應用產品
3.3

2015年5月17日

Router and Multiple Views

  • Router and Multiple Views 介紹
    在angularJS提供一個很強大的功能叫作路由(router),主要應用在切換不同model和views,更容易做出SPA( Single Page Application)註一等級的產品。本章我們介紹如何利用ngRoute的模組切換不同的網頁視圖。
註一: SPA 的概念傳統的 HTML 網頁一樣,需要每做一個動作就整個更新網頁,但是SAP希望可以像視窗軟體一樣,只需要變更顯示的內容而不需更新整個網頁。
  • 載入路由功能
    <head>
         <script src="angular.js" />
        <script src="angular-route.js"/></head>
  • 定義路徑與規畫控制器
    我們利用$routeProvider來切換網頁內容,下列範例定/home, /viewItems
    兩個畫面規畫。在mainApp.controller控制器來切換/home, /viewItems的
    之內容。


    itemController.js
    var mainApp = angular.module("mainApp", ['ngRoute']);

    mainApp.config(function($routeProvider) {
       $routeProvider
            .when('/home', {
                templateUrl: 'home.html',
                controller: 'ItemController'
            })
            .when('/viewItems', {
                templateUrl: 'viewItems.html',
                controller: 'ItemController'
            })
            .otherwise({
                redirectTo: '/home'
            });
    });

    mainApp.controller('ItemController', function($scope) {
        $scope.items = [
            {name: 'apple', city:'New York'},
            {name: 'banana', city:'London'},
        ];

        $scope.message = "Click on the hyper link to view the item list.";
    });
    說明:
    (1)var mainApp = angular.module("mainApp", ['ngRoute']);
    加入ngRoute模組為應用程式

    (2)$routeProvider :用來規化路由,其中when()方法是由path和route當做參數,path為#符號的路徑;route裡面有兩個參數分別為templateUrl用來指定網頁檔案以及controller控制器來指定控制器

    syntx:   when(path, route)

    (3)mainApp.controller: 控制器功能實做


    home.html
    <body ng-controller="ItemController">
        <div class="container">
            <h2> Welcome </h2>
            <p>{{message}}</p>
            <a href="#/viewItems"> View Items List</a>
        </div>   
    </body>

    viewItems.html
    <div class="container">
        <h2> View Items </h2>
        Search:
        <br/>
            <input type="text" ng-model="name" />
        <br/>
        <ul>
            <li ng-repeat="item in items | filter:name">{{item.name}} , {{item.city}}</li>
        </ul>
    </div>

2015年5月13日

Filters

  • 過濾器(Filters)
    angularJS在資料格式顯示方面,他們使用過濾器轉換資料,首先我們需要了解過濾器可以處理範圍:

    過濾器的格式:
    {{ filter_expression | filter : expression : comparator}}

    過濾器類型 說明
    currency 貨幣格式
    filter 搜尋集合符合條件的子集合
    lowercase 轉換成小寫型態
    orderBy 排序
    uppercase 轉換成大寫型態


    (1)currency

    範例: 當宣告currency會補上$的符號

    <body ng-app="myList" >
        <div ng-controller='ListController' >
            <div ng-repeat='item in items'>
                <span>{{item.title}}</span>
                <input ng-model='item.quantity'>
                <span>unit price: {{item.price | currency}}</span>
                <span>total: {{item.price * item.quantity | currency}}</span>
            </div>
        </body>

    <script>
         var myApp = angular.module('myList',[]);
         myApp.controller('ListController', function($scope){
            $scope.items=[
                {title:"apple",quantity:10, price:350},
                {title:"banana",quantity:8,  price:450},
                {title:"star",quantity:7,  price:350}
            ];
           
        
         });
    </script>

    apple    unit price: $350.00 total: $3,500.00
    banana unit price: $450.00 total: $3,600.00
    star       unit price: $350.00 total: $2,450.00



    (2) filter
    範例:過濾符合條件的資料

    <html ng-app="myList">
        <head>
             <script src="angular.js"></script>
        </head>
       
        <body>
            <div ng-controller='ListController' >
             <input ng-model="searchText">
            <div ng-repeat='item in items | filter:searchText'>
                <span>{{item.title}}</span>
                <input ng-model='item.quantity'>
                <span>unit price: {{item.price | currency}}</span>
                <span>total: {{item.price * item.quantity | currency}}</span>
            </div>
        </body>
        </body>
        <script>
         var myApp = angular.module('myList',[]);
         myApp.controller('ListController', function($scope){
            $scope.items=[
                {title:"apple",quantity:10, price:350},
                {title:"banana",quantity:8,  price:450},
                {title:"star",quantity:7,  price:350}
            ];
         });
        </script>
    </html>

    apple unit price: $350.00 total: $3,500.00




    (3)lowercase

    範例: 當輸入apple會自動改為小寫的文字

    <div ng-app="myApp" ng-controller="lowerController">
    <input type="text" name="message" ng-model="message" />
    <p> upper case:{{message | lowercase}} </p>

    </div>

    <script>
    var myApp = angular.module("myApp",[])
    myApp.controller("lowerController", function($scope){
    });

    </script>

    input:
    upper case:apple


(4)orderBy

範例: 當利用ng-repeat印出水果明細,再利用orderBy:'price' 依照單價去排序

<body ng-app='myList' >
        <div ng-controller='ListController'>
            <div ng-repeat="item in items | orderBy:'price'" >
            <span>{{item.title}}</span>
            <input ng-model='item.quantity'>
            <span>{{item.price | currency}}</span>
            <span>total: {{item.price * item.quantity | currency}}</span>
            
        </div>
    </body>
<script>
     var myApp = angular.module('myList',[]);
     myApp.controller('ListController', function($scope){
        $scope.items=[
            {title:"apple",quantity:4, price:350},
            {title:"banana",quantity:4,  price:450},
            {title:"start",quantity:4,  price:350}
        ];
     });
   
</script>

apple    $350.00 total: $1,400.00
start     $350.00 total: $1,400.00
banana $450.00 total: $1,800.00




(5) uppercase

範例: 當輸入apple會自動改為大寫的文字

<div ng-app="myApp" ng-controller="upperController">
<input type="text" name="message" ng-model="message" />
<p> upper case:{{message | uppercase}} </p>

</div>

<script>
var myApp = angular.module("myApp",[])
myApp.controller("upperController", function($scope){
});

</script>

input:
upper case:APPLE

Organizing Dependencies with Modules

  • 工廠模式(Factory)
  • 你可以使用工廠模式建立服務,並傳回資料給模組。
    1.  factory(name,Function())
    2.  factory(name,[], Function() )

    <body  ng-app="myShoppingList">
             <div>
                <table ng-controller="itemsController">
                    <tr ng-repeat="item in items" >
                        <td>{{item.title}}</td>
                        <td>{{item.description}}</td>
                        <td>{{item.price | currency}}</td>
                    </tr>
                </table>
             </div>
        </body>
        <script>
            var myApp = angular.module('myShoppingList',[]);
             myApp.factory('Items', function(){
                 var items = {};
                 items.query = function(){
                    return [
                        {title:"apple", descript:"5 start", price:500},
                        {title:"apple", descript:"3 star",  price:200},
                        {title:"apple", descript:"2 star",  price:100}
                    ];
                 };
                 return items ;
                
             });
             myApp.controller("itemsController", function($scope, Items){
                 $scope.items = Items.query() ;
             })
            
           
        </script>

    apple $500.00
    apple $200.00
    apple $100.00

 

  • Service
    service 常被用來組織或是封裝成一個服務,它有幾個特點:
    (1) 服務寫成的物件只會一個實例

    例子: 我們寫一個baseService當為基本利率換算來轉換水果的價格需要乘上10倍

<body  ng-app="myapp">
         <div>
            <table ng-controller="rateController">
                <tr ng-repeat="item in items" >
                    <td>{{item.name}}</td>
                    <td>{{item.price | currency}}</td>
                </tr>
            </table>
         </div>
    </body>
    <script>

        //基本利率換算
       var m = angular.module("baseService",[]) ;
        m.service("serviceSample",function(){
            this.rate= function(price){
                return  price* 10;   
            }
        });
       
        //轉換水果的價格
        var myapp = angular.module("myapp",["baseService"]);
         myapp.controller('rateController',function($scope, serviceSample){
           
            items = [
                     {name:"apple" , price:serviceSample.rate(20) },
                     {name:"banana", price:serviceSample.rate(30) }
                    ]
           
                return  $scope.items = items    ;
           
            }) ;        
       
    </script>

apple $200.00
banana $300.00

  • provide

2015年5月12日

List、Tables and Other Repeated Elements

  • 複數元素資料
    當我們要顯示出多筆物件的資料時,angular有提供ng-repeat的元素它會複製每一筆資料出來

    範例一
    <html ng-app="myApp">
        <head>
             <script src="angular.js"></script>
        </head>
       
        <body>
            <form ng-controller="fruitController">
                <ul>
                    <li ng-repeat="f in fruit">
                        <a href="/fruit/view/{{f.id}}"> {{f.name}} </a>
                    </li>
               
                </ul>
            </form>
        </body>
       <script>
            var fruit = [{name:"apple",id:"2"},
                             {name:"orange",id:"3"},
                             {name:"watermelon",id:"4"}
                            ]
            var myApp = angular.module('myApp',[]) ;
            myApp.controller('fruitController',function($scope){
                $scope.fruit = fruit;
            })
        </script>
    </html>


  • Hiding and Showing
    當我們需要隱藏或是顯示資訊時,angular提供ng-show和ng-hide兩種方法可以使用,menuState預設
    為隱藏(false),當按下'toggleMenu會更改menuState為顯示(true)。

<html ng-app="myApp">
    <head>
         <script src="angular.js"></script>
    </head>
   
    <body>
        <form ng-controller="hideController">
            <button ng-click='toggleMenu()'>Toggle Menu</button>
            <ul ng-show='menuState.show'>
                <li>menu1</li>
                <li>menu2</li>
            </ul>
        </form>
    </body>
    <script>
        var myApp = angular.module('myApp',[]);
         myApp.controller('hideController', function($scope){
            $scope.menuState = {show:false};
            $scope.toggleMenu = function(){
                $scope.menuState.show =  !$scope.menuState.show;
            }
         });
       
    </script>
</html>

  • menu1
  • menu2

  • Class and Styles

    <html ng-app="myApp">
        <head>
             <script src="angular.js"></script>
             <style>
                .error {
                    background-color: red;
                }
                .warning {
                    background-color: blue;
                }
             </style>
        </head>
       
        <body>
            <form ng-controller="cssController">
                
                <div ng-class="{error:error, warning:warning}" >{{message}}</div>
                <input type="button" ng-click="error()" name="btnerror" value="show error" />
                <input type="button"  ng-click="warning()" name="btnwarning" value="show warning"  />
               
            </form>
        </body>
        <script>
            var myApp = angular.module('myApp',[]);
             myApp.controller('cssController', function($scope){
                
                 $scope.error = function(){
                    $scope.error = true;
                    $scope.warning = false;
                    $scope.message = "It is a error !"
                 }
                
                  $scope.warning = function(){
                    $scope.error = false;
                    $scope.warning = true;
                    $scope.message = "It is a warning !"
                 }
                
             });
           
        </script>
    </html>

    It is a warning !




Templates and Data Binding

  • 樣版(templates)
    使用Angular框架它是一種樣板的開發模式,我們會在HTML網頁上,規劃需要載入內容或是效果,其他交給Angular處理就可以

    <div ng-model=”greeting” >
          {{greeting}}    //->樣板開發方式</div>

  • 資料繫結(Data Binding)
    你可以利用資料繫結去同步更新資料,這裡提供兩種寫法
    (1)
    <p ng-bind="greeting"></p>
    (2)
    <p>{{greeting}}</p>

2015年5月10日

第一個AngularJS程式

  • 開始撰寫第一個程式
    下載Angular套件:https://angularjs.org/

    Image 1

    載入套件:
    <script src="angular.js"></script>

    宣告Angular’s Boundaries
    (1)和(2) 載入的範圍不同,用來告訴Angular該網頁哪個部分需要處理
    (1)載入整個網頁為Template
    <html ng-app>

    </html>
    (2)載入div元素之間為Template
    <html>

    <div ng-app>

    </div>

    </html>
  • 完整的網頁
<html ng-app="myList">
<head>
     <title>My Shopping List</title>
     <script src="angular.js"></script> </head>
     <body ng-controller='ListController'>
          <div >
               <div ng-repeat='item in items'>                   <span>{{item.title}}</span>
                   <input ng-model='item.quantity'>
                   <span>{{item.price | currency}}</span>,
                   <span>總價: {{item.price * item.quantity | currency}}</span>
                   <button ng-click="remove($index)">Remove</button>
               </div>
          </div>
     </body>
<script>
    var myApp = angular.module('myList',[]);
     myApp.controller('ListController', function($scope){
          $scope.items=[
               {title:"國語",quantity:10, price:350},
               {title:"英文",quantity:8,  price:450},
               {title:"公民",quantity:7,  price:350}
          ];
          $scope.remove = function(index) {
               $scope.items.splice(index, 1);
           }
     });
</script>
</html>
說明:
ng-app : 用來告訴Angular該網頁哪個部分需要處理,此範例定義在<html>標簽中表示整個網頁都需要處理,。
ng-controller : 宣告控制器用來處理網頁
ng-repeat : 我們將物品陣列利用item的物件逐一的讀取顯示出來,{{item.title}}為資料繫結(data binding)用來將保持網頁上資料同步。
ng-model :  用來建立quantity與{{item.price * item.quantity | currency}} 的關係,當我們改變物品的數量同時也會改變總價。

MVC

  • Model View Controller (MVC)
    MVC架構在1970提出,模型Model(M)-檢視View(V)-控制Controller(C)三種介面分開,讓程式可以各司其職也讓開發人員可以分工合作,以達到一個較好的開發效率。

    檔案: ex1.html
    <html ng-app="myApp">
    <head>
         <script src="angular.js"></script>
      </head>
         <body >
              <div ng-controller='HelloController'>
                   <p>{{greeting.text}}, World</p>
              </div>
         </body>
    <script>
      
         var myApp = angular.module('myApp',[]);
         myApp.controller('HelloController', HelloController);
    </script>
    </html>
    檔案:controllers.js
    function HelloController($scope) {
         $scope.greeting = { text: 'Hello' };
    }
    說明:
    我們定義HelloController顯示文字為Hello,當載完整個網頁後,Angular框架會根據控制器載入內容物件,結果顯示為 Hello, World。但是除了把controller獨立出來寫成JS檔外,還有另一種寫法為

    方法二:

    var myApp = angular.module('myApp',[]);
    myApp.controller('HelloController', function($(scope){
             $scope.greeting = { text: 'Hello' };
    });





AngularJS介紹


AngularJS由Google 打造的前端 JavaScript 框架,與其他JS框架(ExtJSBackboneJSEmberJSKnockoutJS)
不同,他可以直接延伸現有的 HTML 架構。以下有幾點關注的概念必須了解,對往後要使用AngularJS框架開發應用
網頁會更為快速:

  1. 前端網頁MVC架構:
    在AngularJS將前端AngularJS為控制器 (Controllers) 、檢視 (Views)與模組 (module),控制器可以用來切換不同
    檢視畫面其內容搭配模組 (module) 與 相依性注入 (Dependency Injection) 來實做。當前端網頁也切割為MVC
    架構表示我們可以自由的抽離這些實做,但是也會使開發人員學習複雜度增加。
     
  2. 資料聯結(Data Binding)
    資料繫結很多JS框架都有此功能,我們必須了解單向資料繫結(One-way Data-Binding)雙向資料繫結(Two-
    way Data Binding)
    兩種,單向資料繫結產生檢視之前,將模組與模板先做合併的動作,但是如果有經過一些操
    做改變了模型資料內容,但是檢視上模型並不會改變造成不同步的狀況發生。
    雙向資料繫結改善單向的缺點,不管使用者在網頁上做了甚麼操作,AngularJS都會去偵查檢視的改變,同步去更
    新模型的資料內容。
  3. 相依注入(Dependency Injection,DI)
    相依注入是AngularJS 一個強項,它的目地讓程式的組件切割的更加清楚,主要它利用design pattern的方法來將
    模型靈活的使用,深入了解可以參考Dependency Injection。
  4. 指示指令(Directives)
    在HTML中觸發JavaScript行為的參數,舉例來說
    ex1: <html ng-app="myApp">
    ex2: <div ng-controller='HelloController'>
    ex3: <div ng-repeat='item in items'>