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

Publication

Category

Recent Post

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 윤영식