2016年4月15日 星期五

AngularJS範例說明9-routing mode


  • 標籤模式
    • Hash URL, URL路徑會以#符號開頭。
    • 與config函數中的$routeProvider進行配置。
    <!--標籤模式-->

<div class="pull-left">
      <span><a href="#/">Default Route</a></span>
    </div>
    <div class="pull-right">
      <span ng-hide="mainCtrl.userService.isLoggedIn">
        <a href="#/login">Login</a>
      </span>
      <span ng-show="mainCtrl.userService.isLoggedIn">
        <!-- server-side route, not a client-side route -->
        <a href="/api/logout">Logout</a>
      </span>
    </div>

<script type="text/javascript">
    angular.module('myApp', ['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider
        .when('/', {
            templateUrl: 'views/home.html',
            controller: 'HomeController'
        })
        .when('/login', {
            templateUrl: 'views/login.html',
            controller: 'mainCtrl'
        })
        .when('/api/logout', {
            templateUrl: 'views/logout.html',
            controller: 'mainCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });

    });
    </script>


  • HTML5模式
    • URL看起來與一般server side route無異。
    • 啟用HTML5模式
      • $locationProvider.html5Mode(true)
      • index.html增加含有herf屬性的<base>標籤來告知瀏覽器相關URL的所在位置
      • server side支援url重寫,並確保所有請求都返回index.html(nodejs)
    <!--HTML5模式-->

<html>
  <head>
    <base herf="/app" />
    <title>HTML5 Mode</title>
  </head>
  <body>
    <script type="text/javascript">
        angular.module('myApp', ['ngRoute']).
        config(['$locationProvider', '$routeProvider', function ($locationProvider, $routeProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider
            .when('/', {    //指到<base>設定的地方=>即為/app
                templateUrl: 'views/home.html',
                controller: 'HomeController'
            })
            .otherwise({
                redirectTo: '/'
            });
        }]);
    </script>
  </body>
</html>

AngularJS範例說明8-ng-view、ngRoute、$routeProvider

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js"></script>
    <!--1. include angular-route.js in your HTML-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular-route.js"></script>
    <title></title>
    <meta charset="utf-8" />
</head>
<body ng-app="myApp">

    <!--2. ng-view是由ngRoute提供的一個特殊指令,是routing後視圖模板的作用域-->
    <div ng-view></div>

    <script type="text/javascript">
        //3. load the module in your application
        angular.module('myApp', ['ngRoute']).
        //4. Config區塊使用$routeProvider定義routes
        config(['$routeProvider', function ($routeProvider) {
            $routeProvider
            //AngularJS提供的whenotherwise兩個方法來定義應用的路由
            /*使用when來添加一個特定路由,此方法可以添加兩個參數:when(path, route)
            ex:
                $routeProvider.when(url,{
                    template:string,
                    templateUrl: string,
                    controller: string, function or array,
                    controllerAs: string,
                    redirectTo: string or function,
                    reloadOnSearch: true or false,
                    resolve: object<key, function>
                });

                path:路由路徑,與$location.path(即為當前的URL路徑)進行匹配。可用$routeParams讀取這個參數
                route:配置對象。當路徑匹配成功時,具體該做些什麼。其中屬性包含了controllertemplatetemplateURLresolveredirectToreloadOnSearch

                    controller
                        controller: 'MyController'
                        controller: function($scope) {}
                    template
                        template: '<div><h2>Route</h2></div>'
                    templateURL
                        templateUrl: 'views/template_name.html'
                    redirectTo
                        redirectTo: '/home'
                        redirectTo: function(route,path,search)
                    reloadOnSearch
                        reloadOnSearch:true(default)
                        reloadOnSearch:false
                        $location.search()$location.hash()發生變化時會重新加載路由。
                    resolve
                        載入特定route前,預先執行一個非同步工作
            */
            .when('/', {
                templateUrl: 'views/home.html',
                controller: 'HomeController'
            })
            .when('/temp', {
                template: '<h5>This is template route.</h5>',
                controller: 'TempController'
            })
            .when('/login', {
                templateUrl: 'views/login.html',
                controller: 'LoginController'
            })
            .when('/dashboard', {
                templateUrl: 'views/dashboard.html',
                controller: 'DashboardController',
                resolve: {
                    user: function (SessionService) {
                        return SessionService.getCurrentUser();
                    }
                }
            })
//使用otherwise來定義預設路由
            .otherwise({
                redirectTo: '/'
            });
        }]);
    </script>
</body>
</html>

2016年4月14日 星期四

AngularJS範例說明7-Filter

註:紅字為執行結果
  • 內建 filters
    • Currency:現金格式
      • {{ 123 | currency }} $123.00
    • Filter:找出符合條件者(元素、字元)
      • {{ ['Ari','Lerner','Likes’] | filter:'e' }} ["Lerner","Likes”]
      • {{ [{'name': 'Ari‘,'City': 'San Francisco‘,'favorite food': 'Pizza’},{'name': 'Nate‘,'City': 'San Francisco‘,'favorite food': 'indian food’}] | filter:{'favorite food': 'Pizza'} }} [{"name":"Ari","City":"SanFrancisco","favoritefood":"Pizza"}]
    • LimitTo:取字元(從前面取或從後面取)
      • {{ San Francisco is cloudy | limitTo:3 }} San
      • {{ San Francisco is cloudy | limitTo:-6 }} cloudy
    • Lowercase:轉小寫
      • {{ "San Francisco is cloudy" | lowercase }} san francisco is very cloudy
    • Uppercase:轉大寫
      • {{ "San Francisco is cloudy" | uppercase }} SAN FRANCISCO IS VERY CLOUDY
    • Orderby:排序(有加true時是反向排序)
      • {{ [{'name': 'Ari','status': 'awake'},{'name': 'Q','status': 'sleeping'},{'name': 'Nate','status': 'awake’}] | orderBy:'name' }}[{"name":"Ari","status":"awake"},{"name":"Nate","status":"awake"},{"name":"Q","status":"sleeping"}]
      • {{ [{'name': 'Ari','status': 'awake'},{'name': 'Q','status': 'sleeping'},{'name': 'Nate','status': 'awake’}] | orderBy:'name':true }}[{"name":"Q","status":"sleeping"}, {"name":"Nate","status":"awake"},{"name":"Ari","status":"awake"}]
    • Number:數字格式(逗號分隔、小數位數)
      • {{ 123456789 | number }} 1,234,567,890
      • {{ 1.234567 | number:2 }} 1.23
    • Json:轉成字串
      • {{ {'name': 'Ari', 'City': 'SanFrancisco'} | json }} { "name": "Ari", "City": "SanFrancisco" }
    • Date:日期格式轉換
  • 自定義 filters
    • 實作將第一個字母轉為大寫
    • angular.module('myApp.filters', [])
      .filter('capitalize', function() {
         return function(input) {
         // input是我輸入的字符串
         if (input)
            return input[0].toUpperCase() + input.slice(1);
         }
      });
    • 如何調用
    • {{ 'ginger loves dog treats' | lowercase | capitalize }}
    • 回傳結果
    • Ginger loves dog treats