본문 바로가기

Javascript/Angular.js

CodeSchool Angular.js Level5

레벨 5에서는 모듈과 서비스에 대해서 공부한다.


일단 모듈 나누기부터~


products.js 파일을 만든 후 app.js에 있던 product 관련 내용들을 옮긴다.


products.js

(function() {

  var app = angular.module('store-directives',[]);

  

  app.directive("productDescription", function() {

    return {

      restrict: 'E',

      templateUrl: "product-description.html"

    };

  });


  app.directive("productReviews", function() {

    return {

      restrict: 'E',

      templateUrl: "product-reviews.html"

    };

  });


  app.directive("productSpecs", function() {

    return {

      restrict:"A",

      templateUrl: "product-specs.html"

    };

  });


  app.directive("productTabs", function() {

    return {

      restrict: "E",

      templateUrl: "product-tabs.html",

      controller: function() {

        this.tab = 1;


        this.isSet = function(checkTab) {

          return this.tab === checkTab;

        };


        this.setTab = function(activeTab) {

          this.tab = activeTab;

        };

      },

      controllerAs: "tab"

    };

  });


  app.directive("productGallery", function() {

    return {

      restrict: "E",

      templateUrl: "product-gallery.html",

      controller: function() {

        this.current = 0;

        this.setCurrent = function(imageNumber){

          this.current = imageNumber || 0;

        };

      },

      controllerAs: "gallery"

    };

  });

})();


여기서는 store-directives 라는 이름으로 새 모듈을 만들었다.


그리고 app.js에 dependancy로 store-directives를 추가해준다.

var app = angular.module('gemStore', ['store-directives']);


index.html

<!DOCTYPE html>

<html ng-app="gemStore">

  <head>

    <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

    <script type="text/javascript" src="angular.min.js"></script>

    <script type="text/javascript" src="app.js"></script>

    <script type="text/javascript" src="products.js"></script>

  </head>


  <body ng-controller="StoreController as store">

    <!--  Store Header  -->

    <header>

      <h1 class="text-center">Flatlander Crafted Gems</h1>

      <h2 class="text-center">– an Angular store –</h2>

    </header>


    <!--  Products Container  -->

    <div class="list-group">

      <!--  Product Container  -->

      <div class="list-group-item" ng-repeat="product in store.products">

        <h3>{{product.name}} <em class="pull-right">{{product.price | currency}}</em></h3>


        <!-- Image Gallery  -->

        <product-gallery></product-gallery>


        <!-- Product Tabs  -->

        <product-tabs></product-tabs>

      </div>


    </div>

  </body>

</html>


ng-app에는 메인 모듈인 gemStore만 걸어주면, dependancy 걸려있는 store-directives 모듈은 알아서 가져온다.

단, 이때 products.js 파일은 index.html에 따로 링크를 걸어줘야한다.



그리고 이제 대망의 service다.

지금까지는 껍데기만 공부했다면 이게 알맹이라고 할 수 있지요.


app.js

app.controller('StoreController', ['$http', function($http){

    var store = this;

    store.products = [];

    

    $http.get('/store-products.json').success(function(data){

      store.products = data;

    });


  }]);

angualr에서는 $http, $log, $filter 등 다양한 서비스들을 내장하고 있다. 이것들은 앞에 $ 표시를 붙여서 불러올 수 있다.

$http({ method : 'get', url : '/products.json' });

또는 줄여서

$http.get('products.json', {apiKey : 'myApiKey'} );

이렇게 쓸 수 있다.

둘 모두 promise object인 success()와 error()를 리턴한다.


controller의 두번째 인자는 서비스 사용하는 경우 배열로 만들어서 넘겨주면 된다.

만약 $log 서비스도 필요하다면, 

['$http', '$log', function($http, $log){}]

이런식으로 여러개의 서비스를 넘겨줄 수도 있다.


이렇게 하면 5단계도 끝이다. 

이걸로 angular.js 코스는 완료~!








* 소스는 모두 http://campus.codeschool.com 에서 가져온 겁니다.

'Javascript > Angular.js' 카테고리의 다른 글

CodeSchool Angular.js Level4  (0) 2017.03.09
CodeSchool Angular.js Level3  (0) 2017.03.07
CodeSchool Angular.js Level2  (0) 2017.03.06
CodeSchool Angular.js Level1  (0) 2017.02.27