블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2013. 8. 20. 17:32 AngularJS/Prototyping

iCheck 플러그인은 HTML input의 type이 Checkbox나 Radio 의 모양을 UX 입장에서 직관적으로 만들어 준다. AngularJS하에서 이런 JQuery Plugin을 사용하려면 Directive(지시자) 화하여 사용해야 하는데 어떻게 만드는지 알아보자 




1. Directive 만드는 형식 

  - 사용하려는 HTML 안에서 

<div directiveName ></div>

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


  - AngularJS Directive(지시자) 만들기

    + pluginActivationFunction은 플러그인의 호출하는 펑션이다. 

    + scope.$eval 은 플러그인의 환경값을 넣어주면 된다 

App.directive('directiveName', function() {

    return {

        restrict: 'A',

        link: function(scope, element, attrs) {

            $(element).'pluginActivationFunction'(scope.$eval(attrs.directiveName));

        }

    };

}); 



2. iCheck Directive 만들기 

  - ng-app 모듈에 Directive를 만든다 

    + Radio 박스 선택에 따른 부가화면을 show하거나 hidden 하는 처리를 한다  

    + Attribute로 ngIcheck 지시자를 만들었다. (HTML에서는 ng-icheck 로 사용된다)

    + ifChecked의 iCheck 이벤트를 받았다. iCheck의 Radio를 사용하면서 AngularJS의 Radio 이벤트를 받을 수 없게 되었기 때문이다 

    + Radio의 attribute로 value="file" or "direct" 라는 두개의 Radio 선택 옵션을 주었다. 

    + AngularJS Context안에서 $scope의 값 변경을 인식하기 위하여 $scope.$apply()를 iCheck.on listener의 핸들러 펑션에 호출함.

    + $(element).iCheck(<환경값>); 의 plugin 초기화 펑션을 호출해 주었다 

.directive('ngIcheck', function() {

   return {

       restrict: 'A',

       controller: function($scope, $element) { 

        $element.on('ifChecked', function(event){

 if(event.target.value === 'file') {

  $scope.isFile = true;

  $scope.isDirect = false;

  $scope.$apply();

 } else if(event.target.value === 'direct') {

  $scope.isDirect = true;

  $scope.isFile = false;

  $scope.$apply();

 } else {

  $scope.isFile = false;

  $scope.isDirect = false;

  $scope.$apply();

 }

});

       },

       link: function(scope, element, attrs) {

           $(element).iCheck({

        checkboxClass: 'icheckbox_square-blue', 

        radioClass: 'iradio_square-blue', 

        increaseArea: '20%' 

       });

       }

   };

});


// 중요)

// iCheck를 AngularJS의 Directive로 하지 않고 사용하려면 HTML하단에 해당 script를 넣어준다

// 이렇게 하면 Radio 버튼의 이벤트가 AngularJS Context안에서 작동하지 않기 때문에 AngularJS의 기능을 사용할 수 없다 

// 결국 이렇게 사용하지 않기 위해선 JQuery Plugin을 AngularJS Directive로 만들어 AngularJS Context에서 돌아가게 해주는 것이다

<script>

$(document).ready(function(){

  $('input').iCheck({

    checkboxClass: 'icheckbox_square-blue',

    radioClass: 'iradio_square-blue',

    increaseArea: '20%'

  });

});

</script>


  - HTML에서 사용하기 

    + <input type="radio" name="iCheck" .../> : 여기까지는 iCheck에서 사용함 

    + <input ... value="file" ng-icheck> : AngularJS에서 사용. ng-icheck Attribute를 만다면 AngularJS가 컴파일하고 link하고 이벤트 반응에 대하여 controller에서 처리한다 

    + Radio의 선택에 따라서 ng-show="isFile", ng-show="isDirect"에 따라서 해당 div가 show, hidden 되어 진다 

  <table id="maForm" class="table table-striped table-bordered">

      <thead>

        <tr>

          <th width="25%"><i class="icon-check-sign icon-small"></i> Options</th>

          <th width="75%" class="not-for-mobile"><i class="icon-edit icon-small"></i> Insert Data</th>

        </tr>

      </thead>

      <tbody>

        <tr>

          <td>

            <label>Select Input Method</label> <br>

            <table class="table table-condensed">

              <tr class="active">

                  <td><input type="radio" name="iCheck" value="file" ng-icheck /></td>

                  <td>Upload File</td>

              </tr>

              <tr class="active">

                  <td><input type="radio" name="iCheck" value="direct" ng-icheck /></td>

                  <td>Input Direct</td>

              </tr>

            </table>

          </td>

          <td>

          <!-- input direct data -->

          <div ng-show="isDirect">

  <textarea ng-model="ma.direct" class="form-control" rows="12"></textarea>

  </div>

  <!-- upload file such as .csv -->

  <div ng-show="isFile">

                  <input id="fileupload" ng-model="ma.file" type="file" name="files[]" multiple>

  </div>

          </td>

        </tr>

        <tr>

      <td colspan="2">

  <i class="icon-bar-chart icon-small"></i> Moving Average Chart<br>

  <img src="http://www.placehold.it/880x300/EFEFEF/AAAAAA&amp;text=no+image">

      </td>

        </tr>

      </tbody>

    </table>


  - 결과 : 선택하는 옵션 박스가 iCheck 플러그인을 통하여 좀 더 직관적으로 나오게 되었다

    + 단순한 Radio 옵션

    

    + 변경된 iCheck Radio 옵션

    



<참조> 

  - Correct way to integrate JQuery Plugins in AngularJS 

  - How to convert a jQuery plugin to AngularJS Directive : 유튜브 동영상

  - Directive의 $watch 와 $apply 완벽 이해 : $apply, $digest, $watch 에 대한 상세 설명

  - Thinking in AngularJS : Angular Way 

  - SlideJS Plugins을 Directive로 만드는 유사한 예제

'AngularJS > Prototyping' 카테고리의 다른 글

[AngularJS] Twitter Search 만들기  (0) 2013.04.05
[AngularJS] Todo 목록 만들기  (0) 2013.04.05
[AngularJS] Hello World 만들기  (0) 2013.04.04
posted by 윤영식
2013. 4. 5. 16:27 AngularJS/Prototyping

AngularJS를 가지고 Twitter Search 기능을 프로토타입핑한다. Angular에서는 jsonp를 어떻게 다루는지 살펴보자 



1) Twitter 검색

  - 검색어를 넣고 트위터로 jsonp 검색을 하고 결과를 출력한다


  - angularJS와 angularJS resource 를 사용한다

    + 서버사이드 데이터를 RESTful하게 가져오기 위한 방법을 제공한다

    + API : http://docs.angularjs.org/api/ngResource.$resource (1.1.4 소스)


  - 사전준비 

     + 소스복제 : git clone https://github.com/ysyun/prototyping

     + 트윗소스 : cd prototyping/angularjs/twitter


  - twitter.html 소스

    + <html ng-app="Twitter"> 를 반드시 추가한다. 설정하지 않으면 하기 에러발생. twitter.js에서 모듈명으로 사용


    + twitter.js angular controller 파일을 별도로 코딩한다

    + <div ng-controller="TwitterCtrl" 추가 

    + <input ng-model="searchTerm" 프로퍼티 추가하여 controller 내의 doSearch function 안에서 검색 파라미터로 사용한다 

    + <button ng-click="doSearch()" 추가하여 검색하기 버튼 클릭하면 호출될 function지정

    + <tr ng-repeat 추가 : angular $resource를 통한 jsonp 호출 결과를 리스팅한다 

<!doctype html>

<html lang="en" ng-app="Twitter">
<head>
<meta charset="UTF-8">
<title>AngularJS Hello World Twitter</title>
<script src="http://code.angularjs.org/1.1.4/angular.min.js"></script>
<script src="http://code.angularjs.org/1.1.4/angular-resource.min.js"></script>

<script src="twitter.js"></script>
<link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>

<div ng-controller="TwitterCtrl">
<form class="form-horizontal">
<input type="text" ng-model="searchTerm">
<button class="btn" ng-click="doSearch()">
<i class="icon-search"></i>Search
</button>
</form>

<table class="table table-striped">
<tr ng-repeat="tweet in twitterResults.results">
<td>{{tweet.text}}</td>
</tr>
</table>
</div>

</body>
</html>


  - twitter.js 소스 

    + angular.module : twitter.html에서 <html ng-app="Twitter" 명칭을 넣어줌. $resource를 사용하기 위하여 ngResource 의존

    + $scope.twitter.get() 호출하게 되면 jsonp 방식으로 호출하여 결과값을 가져온다

angular.module('Twitter', ['ngResource']);

function TwitterCtrl($scope, $resource){
$scope.twitter = $resource('http://search.twitter.com/:action',
{action:'search.json', q:'angularjs', callback:'JSON_CALLBACK'},
{get:{method:'JSONP'}});

// $scope.twitterResults = $scope.twitter.get(function(){ alert(' hi dowon jsonp '); });

$scope.doSearch = function () {
$scope.twitterResults = $scope.twitter.get({q:$scope.searchTerm});
}

}



2) 동영상


  - 소스 : https://github.com/ysyun/prototyping/tree/master/angularjs/twitter

posted by 윤영식
2013. 4. 5. 14:36 AngularJS/Prototyping

Backbone 으로 todo 목록을 처음 만들어 보았을 때 이해와 타입핑을 하는데 많은 시간을 소비하였다. Angular를 접하면서 Todo 목록 만들기가 얼마나 쉽고 빠르게 몇분만에 개발되는지 감상해 보자. 직접 해보았는데 20분정도 소요된것 같다. 그간 배운 빅데이터는 이와 같은 쉬운 웹앱기술로 통합되어 스마트 기기에 표현될 수 있겠다. 



1) 할일 목록 만들기 

   - 사전준비 

     + 소스복제 : git clone https://github.com/ysyun/prototyping

     + 투두소스 : cd prototyping/angularjs/todo


   - 할일 목록을 등록하고 완료체크를 하고 완료된 것은 삭제하는 기능을 갖는다

   

  - Bootstrap, Underscore를 이용하고, Angular Controller를 별도 .js로 분리한다 

  - todo.html

    + <html ng-app> 추가

    + <script> : angular.js, underscore.js, todo.js, bootstrap.css 파일을 연결한다

    + <div ng-controller> 추가 : controller function은 todo.js안에 구현 

    + getTotalTodos() : controller function 안에 구현 - 목록이 변경되면 자동 호출되어 바인딩됨 

    + <li ng-repeat> 추가 : todos 목록 배열을 열거한다 

    + <form> 의 <input ng-model="formTodoText"> 속성을 정의하고 controller function에서 사용토록 한다  

    + <button ng-click="clearCompleted()" 추가 : controller function에서 구현한다

<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>AngularJS Hello World using Directives</title>
<script src="http://code.angularjs.org/1.1.4/angular.min.js"></script>
<script src="../../underscore/underscore-min.js"></script>
<script src="todo.js"></script>
<link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="todo.css">
</head>
<body>

<div ng-controller="TodoCtrl">
<h2>Total count : {{getTotalTodos()}}</h2>
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form class="form-horizontal">
<input type="text" ng-model="formTodoText" ng-model-instant>
<button class="btn" ng-click="addTodo()">
<i class="icon-plus"></i>Add
</button>
</form>

<button class="btn-large" ng-click="clearCompleted()">
<i class="icon-trash"></i>Clear Completed
</button>
</div>

</body>
</html>


    + 브라우져에 출력되는 DOM Element 소스 

    


  - todo.css

.done-true{
text-decoration: line-through;
color: grey;
}


  - todo.js

    + todos : 목록 배열

    + function들 정의

function TodoCtrl($scope) {

$scope.totalTodos = 4;

// 가상 데이터를 만든다
$scope.todos = [
{text:'Learn you', done:false},
{text:'build SPA', done:false}
];

// html에서 전체 건수를 return 해 준다
$scope.getTotalTodos = function() {
return $scope.todos.length;
}

// Underscore.js 를 이용하여 done=false 인 것만 배열로 뽑아낸다
$scope.clearCompleted = function() {
$scope.todos = _.filter($scope.todos, function(todo){
return !todo.done;
});
}

// todos 배열에 html에서 입력한 값을 넣어준다
$scope.addTodo = function() {
$scope.todos.push({text:$scope.formTodoText, done:false});
$scope.formTodoText = '';
}
}



2) TodoList 만들기 동영상

 

  - 소스 : https://github.com/ysyun/prototyping/tree/master/angularjs/todo

posted by 윤영식
2013. 4. 4. 17:59 AngularJS/Prototyping
AngularJS의 세계에 빠져보자.  BackboneJS 를 통하여 자유로운 영혼의 Client Side MV* framework 맛 보았다면 이제 AngularJS를 통하여 좀 더 절제되고 Fast Creating 가능한 방법에 대해 고민해 볼 때가 된 것 같다. 커뮤니티를 통하여 성숙하고 있고, 좋은 문서와 구글이라는 든든한 백그라운드까지 갖추고 있어서 무한한 성장 가능성을 가지고 있는 프레임워크라고 본다


1) Hello World
  - 구글 CDN 참조
  - 소스
<!doctype html>
<html lang="en" ng-app>
<head>
<meta charset="UTF-8">
<title>AngularJS Hello World</title>
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>

<script>
function DowonController($scope) {

$scope.DowonProperty = "YoungSik";
}
</script>

<div ng-controller="DowonController">

<input type="text" ng-model="DowonProperty" ng-model-instant/>
Hello World

{{DowonProperty}}

</div>

</body>
</html>
 
  - 코딩 순서
    + angularJS CDN script 태그 추가 
    + <html ng-app> 추가
    + <div ng-controller> 추가 
    + controller function 구현 : $scope에 속성추가/설정
    + ng-model 추가 
    + {{ property }} 클라이언트 템플릿 추가 
    + 수행 : WOW!!!

  - 이해하기 
    + ng-app를 선언한 DOM 하위는 angular를 통하여 제어가 가능하다. 
    + ng-model을 HTML안에서 선언하면 controller function에서 프로퍼티를 사용할 수 있다
    + controller function에서 프로퍼티를 선언하면 HTML안에서 사용할 수 있다
    + 결국 Angular.js 는 양방향 Live Stream(Dynamic) binding을 가능하게 해준다  


2) 동영상
    


  - 소스 : https://github.com/ysyun/prototyping/blob/master/angularjs/hellworld.html



<참조> 

  - 동강 모음 http://johnlindquist.com/

  

  - 페이스북 공개그룹 : https://www.facebook.com/groups/frontiner/permalink/525021784200620/


AngularJS Hello World 
http://www.youtube.com/watch?v=uFTFsKmkQnQ&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

AngularJS - Getting Started - Google+
https://plus.google.com/communities/115368820700870330756/stream/f1fab692-830e-4341-b010-d0078e18719f

1. Devoxx 2012: AngularJS 
http://www.youtube.com/watch?v=4EVBg1pNdtc&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

2. Mastering AngularJS - 1. Introduction 
http://www.youtube.com/watch?v=DfstuptCfUo&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

3. Mastering AngularJS - 2. Using Directives .....감동의 도가니탕
http://www.youtube.com/watch?v=2SZQslQOgNg&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

4. AngularJS Tutorial .....감동의 도가니탕
http://www.youtube.com/watch?v=WuiHuZq_cg4&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

5. AngularJS Twitter Search 
http://www.youtube.com/watch?v=IRelx4-ISbs&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

6. AngularJS - Directive Tutorial 
http://www.youtube.com/watch?v=Yg-R1gchccg&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

7. AngularJS - Custom Components - Part 1 
http://www.youtube.com/watch?v=A6wq16Ow5Ec&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

8. AngularJS - Custom Components - Part 2 
http://www.youtube.com/watch?v=nKJDHnXaKTY&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

9. AngularJS - Communicating Between Controllers 
http://www.youtube.com/watch?v=1OALSkJGsRw&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

10. AngularJS and DOM Manipulation 
http://www.youtube.com/watch?v=bk-CC61zMZk&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

11. AngularJS - Handy Tricks With Developer Tools ...어려워 나중에
http://www.youtube.com/watch?v=4TM6wG9UW7s&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

12. AngularJS Routing ...............................................................내일은 여기서부터
http://www.youtube.com/watch?v=5uhZCc0j9RY&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

13. AngularJS - Behave like Gmail using Routes with Resolve 
http://www.youtube.com/watch?v=P6KITGRQujQ&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

14. AngularJS + Chosen Plugin = Awesome 
http://www.youtube.com/watch?v=8ozyXwLzFYs&list=PL1w1q3fL4pmgqpzb-XhG7Clgi67d_OHXz

posted by 윤영식
prev 1 next