架構分解介紹

當處理相同事情的 directive 變多,就可以考慮再將這部分獨立成一份檔案
(function(){
    var app = angular.module('store', [ ]);
    app.controller('StoreController', function(){....});
    app.directive('productTitle', function(){...});
    app.directive('productGallery', function(){...});
    app.directive('productPanels', function(){...});
    ....
})();
中間的部分就可以考慮獨立出來到新的 js 檔案(e.g.products.js)中,並給予一個新的 module 的名稱
(function(){
    var app = angular.module('store-products', [ ]);
    app.directive('productTitle', function(){...});
    app.directive('productGallery', function(){...});
    app.directive('productPanels', function(){...});
})();
這時候,原本的 module 就需要增加一個依賴的 module(剛剛獨立出來的 module)
var app = angular.module('store', [ ]);
變為
var app = angular.module('store', ['store-products']);
當然不要忘了在原本的 HTML 頁面,include 獨立出來的 JS 檔
<!DOCTYPE html>
<html ng-app="store">
    <head> . . . </head>
    <body ng-controller="StoreController as store">
        . . .
        <script src="angular.js"></script>
        <script src="app.js"></script>
        <script src="products.js"></script>
    </body>
</html>
以這次的例子來看,最好的 module 與功能區分
  • app.js - top-level module attached via ng-app
  • products.js - all the functionality for products and only products

取得Server資料

(function(){
    var app = angular.module('store', ['store-products']);
    app.controller('StoreController', function(){
        this.products = [
            {name: '...', price: 1.99, ...},
            {name: '...', price: 1.99, ...},
            {name: '...', price: 1.99, ...},
            ....
        ];
        . . .
    });
})();
將中間 JSON 格式的部分,改以從 Server 接收資料,如下使用 Get 為例
(function(){
    var app = angular.module('store', ['store-products']);
    app.controller('StoreController', ['$http', function($http)]{
        //this.products = ???;
        var store = this;
        store.products = []; //initizalize to an empty array
        $http.get('/products.json').success(function(data){
            //??? = data;
            store.products = data;
        });
    });
})();
基本 Get method $http({ method: 'GET', url: '/products.json' }); 用法同 $http.get('/products.json', { apiKey: 'myApiKey' }); 關於 $http 的相關用法 $http.post('/path/to/resource.json', { param: 'value' }); $http.delete('/path/to/resource.json'); $http({ method: 'OPTIONS', url: '/path/to/resource.json' }); $http({ method: 'PATCH', url: '/path/to/resource.json' }); $http({ method: 'TRACE', url: '/path/to/resource.json' });
文章標籤
全站熱搜
創作者介紹
創作者 soarlin 的頭像
soarlin

每天都有新鮮事

soarlin 發表在 痞客邦 留言(0) 人氣(664)