ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [AugularJS] 2. AugularJS 살펴보기 - AngularJS 강좌
    Web/AngularJS 2016. 1. 15. 16:28

    AngularJS 살펴보기




     1. To-Do 웹 어플리케이션

      AngularJS를 간단히 살펴보기 위해서는 To-Do 어플리케이션을 구현해보는 것입니다. 


      이번 장에서 간단하게 할 일을 추가, 수정할 수 있는 웹을 AngularJS를 통해서 작성해 보겠습니다.


      todo 폴더를 생성하여, index.html을 아래와 같이 작성합니다.




     * index.html


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <title> My To-Do App</title>
        </head>
        <body>
            <h1>AngularJS To-Do App</h1>
        </body>
    </html>
    cs




      여기까지 작성 후, 트위터 Bootstrap을 적용하겠습니다. 


    http://getbootstrap.com/ 에 접속해서 내려받아서 라이브러리에 추가할 수 있지만, CDN을 통해서 적용할 수도 있습니다.


      위에서 작성한 index.html의 head 태그안에 추가해줍니다. 그리고 body 태그에 class로 well을 지정해 주면 적용된 것을 확인하실 수 있습니다.

      



     * index.html

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <title> My To-Do App</title>
        </head>
        <body class="well">
            <h1>AngularJS To-Do App</h1>
        </body>
    </html>
    cs



     



      다음으로 HTML 구조를 잡기위해 정리를 하겠습니다. 주요 기능은 아래와 같이 나열됩니다.

      - 할 일 목록 보이기

      - 할 일 등록

      - 완료된 일 보관 가능




      먼저, 정적인 페이지로 구성하여 웹 페이지의 형태를 구축하겠습니다.




     * index.html


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8"/>
            <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <title> My To-Do App</title>
        </head>
        <body class="well">
            <h1>AngularJS To-Do App</h1>
            
            <p>전체 할 일 <strong>2</strong>개 / 남은 할 일 <strong>1</strong>개
                [<a href="">보관하기</a>] </p>
            
            <ul class="list-unstyled">
                <li class="checkbox"><input type="checkbox">AngularJS 학습</li>
                <li class="checkbox"><input type="checkbox">개인 프로젝트 작성</li>
            </ul>
            
            <form name="newItemForm" class="form-inline" action="">
                <div class="form-group">
                    <label class="sr-only" for="newItemText">새로운 할 일</label>
                    <input type="text" class="form-control" name="newItemText" placeholder="새로운 할 일">
                </div>
                <button type="submit" class="btn btn-default">추가</button>
            </form>
        </body>
    </html>
    cs






     1-1. AngularJS 적용

      프레임워크를 적용하기 위해 todo폴더 내에 libs 폴더를 만들고 다운받은 angular.js 파일을 옮깁니다. 그리고 <script> 태그를 이용하여 추가해줍니다.



    1
    2
    3
    4
    5
    6
        <head>
            <meta charset="UTF-8"/>
            <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <script src="libs/angular.min.js"</script>
            <title> My To-Do App</title>
        </head>
    cs



      다음으로 html 태그에 ng-app 속성을 추가해줍니다. ng-app 속성을 추가하면 정적인 페이지에서 AngularJS 웹 어플리케이션으로 변경됩니다.


      다음으로 body 태그에 ng-init 속성에 "appName="AngularJS To-Do App"으로 설정합니다.

     


     * index.html


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <!DOCTYPE html>
    <html ng-app>
        <head>
            <meta charset="UTF-8"/>
            <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <script src="libs/Angular/angular.js"></script>
            <title> My To-Do App</title>
        </head>
        <body class="well" ng-init="appName='AngularJS To-Do APP'">
            <h1>{{appName}}</h1>
            
            <p>전체 할 일 <strong>2</strong>개 / 남은 할 일 <strong>1</strong>개
                [<a href="">보관하기</a>] </p>
            
            <ul class="list-unstyled">
                <li class="checkbox"><input type="checkbox">AngularJS 학습</li>
                <li class="checkbox"><input type="checkbox">개인 프로젝트 작성</li>
            </ul>
            
            <form name="newItemForm" class="form-inline" action="">
                <div class="form-group">
                    <label class="sr-only" for="newItemText">새로운 할 일</label>
                    <input type="text" class="form-control" name="newItemText" placeholder="새로운 할 일">
                </div>
                <button type="submit" class="btn btn-default">추가</button>
            </form>
        </body>
    </html>
    cs





      브라우저를 열어 확인하면 기존의 웹과 유사한 화면이 나타나게 됩니다.







      위 코드를 설명하자면, html 태그의 ng-app 지시자는 해당 HTML 페이지가 AngularJS 기반 웹 어플리케이션이라는 것을 선언합니다. body 태그의 ng-init 속성에서는 appName이라는 변수에 문자열을 담는 역할을 합니다. {{ appName }} 부분에서 appName 변수의 문자열로 치환되는 것입니다.





      1-2. 컨트롤러를 이용한 뷰 조작

       동적인 페이지를 구성하기 위해 가상 데이터를 지정하여 불러오는 식으로 구축해 보겠습니다. 아래 app.js를 작성한 뒤, head 태그에서 script 태그를 이용해서 불러옵니다.



     * app.js

      

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var todoList = [
        { done: true, title: "AngularJS 학습"},
        { done: false, title: "TEPS 학습"},
        { done: true, title: "jQuery 스터디"},
        { done: false, title: "프로젝트 구상"}
    ];
     
    function todoCtrl($scope) {
        
    }
    cs




      index.html의 ng-init 부분을 삭제하고 ng-controller로 대체한 뒤 body 태그를 아래처럼 작성합니다. 또한, html 태그의 ng-app 속성에 todo를 지정해 줍니다.



     * index.html



    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <!DOCTYPE html>
    <html ng-app="todo">
        <head>
            <meta charset="UTF-8"/>
            <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <script src="libs/Angular/angular.js"></script>
            <script src="app.js"></script>
            <title> My To-Do App</title>
        </head>
        <body class="well" ng-controller="todoCtrl">
            <h1>{{appName}}</h1>
            
            <p>전체 할 일 <strong>2</strong>개 / 남은 할 일 <strong>1</strong>개
                [<a href="">보관하기</a>] </p>
            
            <ul class="list-unstyled">
                <li class="checkbox"><input type="checkbox">AngularJS 학습</li>
                <li class="checkbox"><input type="checkbox">개인 프로젝트 작성</li>
            </ul>
            
            <form name="newItemForm" class="form-inline" action="">
                <div class="form-group">
                    <label class="sr-only" for="newItemText">새로운 할 일</label>
                    <input type="text" class="form-control" name="newItemText" placeholder="새로운 할 일">
                </div>
                <button type="submit" class="btn btn-default">추가</button>
            </form>
        </body>
    </html>
    cs




      이렇게 하고 페이지를 로드하면 {{appName}} 그대로 출력됩니다. todoCtrl 함수 내에서 appName에 대한 변수를 선언하여 지정해줘야 합니다. 아래와 같이 지정해주세요. 그래도 안된다면 head 태그에서 app.js를 불러왔는지 확인해주세요.

     


     * app.js


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var todoList = [
        { done: true, title: "AngularJS 학습"},
        { done: false, title: "TEPS 학습"},
        { done: true, title: "jQuery 스터디"},
        { done: false, title: "프로젝트 구상"}
    ];
     
    var app = angular.module("todo",[]);
    app.controller("todoCtrl"function($scope) {
        $scope.appName = 'AngJS ToDo App';
        $scope.todoList = todoList;    
    });
     
    cs




     이렇게 하고나면 todoList 배열의 자료들을 이용할 수 있습니다. 이번 index.html에는 ng-repeat와 ng-model 속성을 추가해서 수정하도록 하겠습니다.




     * index.html


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    <!DOCTYPE html>
    <html ng-app="todo">
        <head>
            <meta charset="UTF-8"/>
            <link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
            <script src="libs/Angular/angular.js"></script>
            <script src="app.js"></script>
            <title> My To-Do App</title>
        </head>
        <body class="well" ng-controller="todoCtrl">
            <h1>{{appName}}</h1>
            
            <p>전체 할 일 <strong>2</strong>개 / 남은 할 일 <strong>1</strong>개
                [<a href="">보관하기</a>] </p>
            
            <ul class="list-unstyled">
                <li ng-repeat="todo in todoList" class="checkbox">
                    <input type="checkbox" ng-model="todo.done">{{todo.title}}
                </li>
            </ul>
            
            <form name="newItemForm" class="form-inline" action="">
                <div class="form-group">
                    <label class="sr-only" for="newItemText">새로운 할 일</label>
                    <input type="text" class="form-control" name="newItemText" placeholder="새로운 할 일">
                </div>
                <button type="submit" class="btn btn-default">추가</button>
            </form>
        </body>
    </html>
    cs









      배열을 반복문을 통해서 간결하게 작성하였습니다. 동적으로 작성이 가능하다는 점을 어필하려고 하는 예제입니다. li 태그 내의 ng-repeat 속성을 통해서 todoList 내의 요소만큼 li 태그를 생성하게 되고, 내부의 ng-model의 todo.done과 todo.title을 통해서 각 요소의 속성을 출력했습니다.






     

      1-3. ToDo App 나머지 기능 구현

       나머지 기능인 할 일 등록과 완료한 일 보관 기능을 추가로 구현하도록 합시다. 


       추가 버튼 라인에 ng-click 속성을 추가해 줍니다.



    1
    2
    <button type="submit" class="btn btn-default" ng-click="addNewTodo(newTitle)">추가</button>
     
    cs




       위에서 추가된 ng-click 내의 속성은 즉, app.js에서 추가해야할 함수인 것입니다.


       위의 코드를 참고해서 아래의 app.js 처럼 작성하게 되는 것입니다.



     * app.js


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    var todoList = [
        { done: true, title: "AngularJS 학습"},
        { done: false, title: "TEPS 학습"},
        { done: true, title: "jQuery 스터디"},
        { done: false, title: "프로젝트 구상"}
    ];
     
    var app = angular.module("todo",[]);
    app.controller("todoCtrl"function($scope) {
        $scope.appName = 'AngJS ToDo App';
        $scope.todoList = todoList;    
        
        $scope.addNewTodo = function(newTitle) {
            todoList.push({done: false, title:newTitle});
            $scope.newTitle = '';
        };
    });
     
    cs




       위에서 보면 newTitle이라는 인자를 받아야 하는데, 이 인자는 index.html에서 넘겨주는 인자입니다. 그러나 어떤 태그에서도 newTitle이라는 인자를 취급하는 곳이 없습니다. 하지만, 웹 페이지에서 보면 딱 봐도 어디서 넘겨줄지 알 수 있습니다. 


       즉, 새로운 할 일이라고 되어있는 텍스트 창에서 받아서 넘겨줘야 합니다. 아래와 같이 ng-model 속성을 추가해줍니다.



    1
    2
     
    <input type="text" class="form-control" name="newItemText" placeholder="새로운 할 일" ng-model="newTitle">
    cs




       이렇게 수정한 뒤, 잘 돌아가는 지 웹에서 확인해보세요. 구현 후 추가된 것만 확인되고 바로 원본으로 돌아가게 됩니다. 직접적인 이유는 버튼을 누름과 동시에 다시 불러오는 데, 그때 진짜로 해당 데이터가 삽입이 된게 아니기 때문에 원본 그대로 출력되는 것입니다.



       다음은 보관하기 기능을 추가하기 위해 아래 index.html 부분처럼 수정합니다.



    1
    2
    <p>전체 할 일 <strong>2</strong>개 / 남은 할 일 <strong>1</strong>개
                [<a href="" ng-click="achieve()">보관하기</a>] </p>
    cs




       achieve() 함수를 추가해주기 위해 app.js 파일에 코드를 추가합니다.



     * app.js


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    var todoList = [
        { done: true, title: "AngularJS 학습"},
        { done: true, title: "jQuery 스터디"},
        { done: false, title: "프로젝트 구상"}
    ];
     
    var app = angular.module("todo",[]);
    app.controller("todoCtrl"function($scope) {
        $scope.appName = 'AngJS ToDo App';
        $scope.todoList = todoList;    
        
        $scope.addNewTodo = function(newTitle) {
            todoList.push({done: false, title:newTitle});
            $scope.newTitle = '';
        };
        
        $scope.achieve = function() {
            for (var i = $scope.todoList.length - 1; i >= 0; i--) {
                if ($scope.todoList[i].done) {
                    $scope.todoList.splice(i, 1);
                }
            }
        };
    });
     
    cs




      다음으로 남은 일의 개수를 처리하는 부분을 수정해야 하는데, 이 부분 또한 함수 작성과 간단한 변수 필드로 수정이 됩니다.


    1
    2
    3
     
    <p>전체 할 일 <strong>{{todoList.length}}</strong>개 / 남은 할 일 <strong>{{remain()}}</strong>개
                [<a href="" ng-click="achieve()">보관하기</a>] </p>
    cs





      전체 할 일은 할 일 리스트 배열의 전체 크기를 가져오는 todoList.length로 해결이 되고, 남은 할 일을 계산해야 합니다.


      remain() 함수를 app.js에 작성해주세요.



     * app.js


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    var todoList = [
        { done: true, title: "AngularJS 학습"},
        { done: true, title: "jQuery 스터디"},
        { done: false, title: "프로젝트 구상"}
    ];
     
    var app = angular.module("todo",[]);
    app.controller("todoCtrl"function($scope) {
        $scope.appName = 'AngJS ToDo App';
        $scope.todoList = todoList;    
        
        $scope.addNewTodo = function(newTitle) {
            todoList.push({done: false, title:newTitle});
            $scope.newTitle = '';
        };
        
        $scope.achieve = function() {
            for (var i = $scope.todoList.length - 1; i >= 0; i--) {
                if ($scope.todoList[i].done) {
                    $scope.todoList.splice(i, 1);
                }
            }
        };
        
        $scope.remain = function() {
            var remainCount = 0;
            angular.forEach($scope.todoList, function(value, key) {
                if (value.done == false) {
                    remainCount++;
                }
            });
            
            return remainCount;
        };
    });
     
    cs











     






    * 이 포스팅은 '시작하세요! AngularJS 프로그래밍'을 바탕으로 작성하였습니다.



    댓글

Designed by Tistory.