AngularJS 튜토리얼 - 베스트셀러 예제 5

Jmnote (토론 | 기여)님의 2015년 7월 19일 (일) 13:41 판 (→‎index.html)

1 index.html

<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="//code.angularjs.org/1.2.28/angular-route.min.js"></script>
</head>
<body ng-app="BestsellerApp5">

<div class="header">
  <a href="#">이달의 베스트셀러</a>
</div>

<div ng-view></div>

<!-- Modules -->
<script src="js/app.js"></script>

<!-- Controllers -->
<script src="js/controllers/HomeController.js"></script>
<script src="js/controllers/BookController.js"></script>

<!-- Services -->
<script src="js/services/books.js"></script>

<!-- Directives -->

</body>
</html>

2 js/app.js

var app = angular.module('BestsellerApp5', ['ngRoute']);

app.config(function ($routeProvider) {
  $routeProvider
    .when('/', {
      controller: "HomeController",
      templateUrl: "views/home.html"
    })
    .when('/books/:id', {
      controller: 'BookController',
      templateUrl: 'views/book.html'
    })
    .otherwise({
      redirectTo: '/'
    });
});

3 js/controllers/HomeController.js

app.controller('HomeController', ['$scope', 'books', function($scope, books) {
  books.success(function(data) {
    $scope.books = data;
  });
}]);

4 js/controllers/BookController.js

app.controller('BookController', ['$scope', 'books', '$routeParams', function($scope, books, $routeParams) {
  books.success(function(data) {
    $scope.detail = data[$routeParams.id];
  });
}]);

5 js/services/books.js

app.factory('books', ['$http', function($http) {
  return $http.get('http://zetawiki.com/json/books.json')
         .success(function(data) {
           return data;
         })
         .error(function(data) {
           return data;
         });
}]);

6 views/home.html

<div class="main">
  <h2>책 목록</h2>

  <div ng-repeat="book in books">
    <a href="#/books/{{$index}}">
      <p> {{ book.name }} ({{ book.author }}) </p>
    </a>
  </div>

</div>

7 views/book.html

<div class="book">
  <h2>{{ detail.name }}</h2>
  <p>{{ detail.author }} 지음</p>
  <p>{{ detail.price | number }}원</p>
</div>

8 테스트

9 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}