SlideShare una empresa de Scribd logo
1 de 52
AngularJS 교육
고재도
WebFrameworks.kr
• GDG Korea WebTech 운영자
• 표준프레임워크 오픈 커미터 리더
• 시작하세요 AngularJS 프로그래밍 집필
• kt 연구소, IoT 플랫폼 개발
고재도
AngularJS 구조
템플릿 작성
<body>
<div ng-controller="sampleCtrl">
고객 목록
<ul>
<li ng-repeat="user in userList">
<input type="number" ng-model="user.age"> {{user.name}}
</li>
</ul>
<div>나이 합계 : {{userList[0].age + userList[1].age}}</div>
</div>
</body>
$scope.userList = [
{name:'제이', age:25},
{name:'블레어', age:28}
];
반복적인 데이터 표현 템플릿
<input type="radio" ng-model="color" value="red"> 빨간색 <br>
<input type="radio" ng-model="color" value="green"> 녹색 <br>
<div ng-switch="color">
<div ng-switch-when="red" class="box red"></div>
<div ng-switch-when="green" class="box green"></div>
<div ng-switch-default="" class="box black"></div>
</div>
<div>
약관에 동의: <input type="checkbox" ng-model="checked" ng-init="checked=false">
<br>
동의하면 다음으로 진행됩니다.
<button ng-if="checked">다음</button>
</div>
조건적인 데이터 표현 템플릿
<form name="sampleForm" ng-init="name = '철수'">
이름 : <input type="text" name="name" ng-model="name" ng-maxlength="3" ng-required="true">
<span class="error" ng-show="sampleForm.name.$error.required">필수입력</span>
<br>
핸드폰 번호: <input type="text" name="tel" ng-model="tel" ng-pattern="/^d{3}-d{3,4}-d{4}$/">
<span class="error" ng-show="sampleForm.tel.$error.pattern">
000-0000-0000
</span>
</form>
폼과 유효성 검사 템플릿
<script type=“text/javascript">
function mainCtrl($scope){
$scope.message = "";
$scope.eventCnt = 0;
$scope.handleEvt = function(message) {
$scope.message = message;
$scope.eventCnt++;
}
}
</script>
<body ng-controller="mainCtrl">
<div class="box" ng-click="handleEvt('박스 클릭됬다.')">click</div>
<div class="box" ng-mousedown="handleEvt('박스 mousedown 이벤트 발생.')">mousedown</div>
<div class="box" ng-mouseenter="handleEvt('박스 mouseenter 이벤트 발생.')">mouseenter</div>
<div class="box" ng-mousemove="handleEvt('박스 mouseenter 이벤트 발생.')">mousemove</div>
change : <input type="text" ng-model="inputText" ng-change="handleEvt('입력 박스의 값이 변경되었다.')">
keydown : <input type="text" ng-model="inputText2" ng-keydown="handleEvt($event.keyCode+'키코드 눌러짐')">
<p>{{message}} {{eventCnt}}</p>
</body>
이벤트 처리 템플릿
템플릿 = 표현식 + 지시자
표현식
예제
• {{ 1+2 }}
• {{ 3*10 | currency }}
• {{ user.name }}
특징
• Scope 객체 기준으로 속성들을 검사한다. (window 로부터가 아니라…)
• Null 에러를 무시한다. ({{a.b.c}} vs {{((a||{}).b||{}).c}})
• 조건문은 올 수 없다.
• 필터들과 함께 쓰인다. ({{ 3*10 | currency }})
.
Angular가 제대로 실행 되지 않을 경우 브라우저에 {{ 표현식 }}이 그대로 보이게 된다.
ng-bind를 이용하면 이를 방지할 수 있다.
a, form, input, ngApp, ngBind, ngChange, ngClass,
ngClick, ngController, ngCloak, ngDbclick, ngDisabled,
ngHide, ngHref, ngInclude, ngModel, ngMousedown,
ngRepeat, ngView, ...
BUILT-IN DIRECTIVE
자바스크립트 작성
제이쿼리로 MVC 코드
<body ng-controller="userMgtCtr">
<div>
<label>부서</label>
<select ng-model="sObj.deptId" ng-options="d.deptId as d.deptNm for d in deptList">
<option value="">선택</option>
</select>
<label>직급</label>
<select ng-model="sObj.posId" ng-options="p.posId as p.posNm for p in posList">
<option value="">선택</option>
</select>
<button ng-click="find(sObj)">검색</button>
</div>
<div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<td>사번</td>
<td>이름</td>
<td>부서</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in userList">
<td>{{user.userId}}</td>
<td>{{user.userNm}}</td>
<td>{{user.deptCd}}</td>
</tr>
</tbody>
</table>
</div>
</body>
angular.module(‘mvcApp’,[])
.controller('userMgtCtr', [‘$scope','$http', function ($scope, $http) {
$scope.sObj={deptId:'',posId:''};
$scope.deptList = [
{ deptId: '001', deptNm: '부서A'},
{ deptId: '002', deptNm: '부서B'}
];
$scope.posList = [
{ posId: '001', posNm: '사원'},
{ posId: '002', posNm: '대리'}
];
$scope.find = function (sObj) {
$http({
method: 'GET', url: 'user.json',
params: { deptId: sObj.deptId, posId: sObj.posId }
})
.success(function(data, status, headers, config) {
$scope.userList = data;
});
};
}]);
제이쿼리로 MVC 코드
MVC 구조
템플릿 뷰데이터 +
<ul>
<li ng-repeat="user in userList">
<input type="number" ng-model="user.age">
{{user.name}}
</li>
</ul>
<div>
나이 합계 : {{userList[0].age + userList[1].age}}
</div>
=
사용자 화면 값 변경
$scope.userList = [
{name:'제이', age:25},
{name:'블레어', age:28}
];
SCOPE
• 뷰와 컨트롤러를 이어주는 단위
• 모델의 개념
SCOPE 타입
function Scope(){
}
Scope.prototype.$watch
Scope.prototype.$digest
Scope.prototype.$apply
…
var $scope = new Scope()
SCOPE의 생성
ng-app
ng-controller
ng-repeat
ng-view
ng-include
…
$scope.$new
모듈과 서비스
모듈
Module
해당 모듈이 사용하는 다른 모듈
문자열 배열로 작성
angular.moudle(‘UserMnge’)
모듈 함수를 2번째 인자가 없이
호출하면 등록된 모듈 인스턴스 반환
모듈 초기화 단계
angular.moudle(‘UserMnge’)
.config(function(){
….
});
angular.moudle(‘UserMnge’)
.run(function(){
….
}
모듈의 설정단계
- 서비스 프로바이더, 서비스 상수 주입
- 필터, 서비스, 펙토리, 벨류 주입 불가
모듈의 실행단계
- 필터, 서비스, 펙토리, 벨류 주입
(서비스 인스턴스 주입)
- 메인 메소드와 같다고 보면됨
서비스
AngularJS의 컨트롤러, 지시자, 필터 그리고 다른 서비스에서 재사용 가능한 컴포넌트(대부분 UI 없이)를
서비스라 함
서비스는 다음과 같은 특징을 가짐
• 애플리케이션 공통 로직으로서의 서비스
• 싱글톤Singleton으로서의 서비스
• 커뮤니케이션 허브hub로서의 서비스
• 의존성 주입 대상Injectable Dependencies으로서의 서비스
서비스 생성 방법
app.constant
app.value
app.service
app.factory
app.config
There are only three ways how an object or a function can get a hold of its dependencies:
The dependency can be created, typically using the new operator.
The dependency can be looked up by referring to a global variable.
The dependency can be passed in to where it is needed.
(출처 : http://docs.angularjs.org/guide/di)
강력한 의존 관계의 JavaScript 예제
의존관계 주입 #1
Root Scope
UserMnge
$provide.
factory(‘UserResource’, …)
$injector
(Dependency Injector)
controller('mainCtrl',
function($scope, UserResource) { … }
)
mainCtrl Scope
userList : Array
상속
find
주입
의존관계 주입 #2
moduel.controller('mainCtrl',function($scope, UserResource) {
…
$scope.search = function() {
…
$scope.userList = UserResource.query({q : query});
};
$scope object UserResource Object
• DI는 자신이 사용하는 오브젝트에 대한 선택과 생성 제어권을 외부로 넘기고 자신은 수동적으로 주입
받은 오브텍트를 사용하게 된다.
• 이는 특히 Unit 테스트 작성에 큰 도움을 준다. 사용하는 오브젝트의 Mock을 만들어서 주입이 가능하기
때문이다.
$scope
Mock object
UserResource
Mock Object
Unit Test 시실제 사용 시
의존관계 주입 #3
angular.module('sampleApp', []).
constant('PI', 3.14159).
config(function (CalProvider, PI) {
CalProvider.setDefaultRadius(5);
console.log(PI);
}).
directive('circle', ['Cal','PI',function (Cal,PI) {
//생략..
}])
CONSTANT
angular.module('sampleApp', []).
value('AppNm', 'demo app').
controller('mainCtrl',function($scope, AppNm) {
$scope.appNm = AppNm;
});
VALUE
function Calculator () {
this.lastValue = 0;
this.add = function(a,b) {
var returnV = a+b;
this.lastValue = returnV;
return returnV;
};
this.minus = function(a,b) {
var returnV = a-b;
this.lastValue = returnV;
return returnV;
};
}
angular.module('sampleApp', []).
service('Calculator', Calculator).
controller('mainCtrl',function($scope, Calculator) {
$scope.val1 = Calculator.add(10,3);
$scope.val2 = Calculator.minus(20,10);
});
SERVICE
app.factory('Foo', function(cnt) {
return function(start) {
this.cnt = start;
this.inc = function(quan) {
this.cnt += quan;
};
};
});
app.controller('MainCtrl', function($scope, cnt, Foo) {
$scope.cnt = name;
$scope.foo = new Foo(1);
$scope.inc = function() {
$scope.foo.inc(1);
};
});
FACTORY
angular.module('sampleApp', []).
provider('Logger', function () {
function Logger(msg) {
if(checkNativeLogger) console.log(msg);
}
Logger.debug = function(msg) { if(checkNativeLogger) console.debug(msg); };
Logger.info = function(msg) { if(checkNativeLogger) console.info(msg); };
function checkNativeLogger() {
if(console) return true;
return false;
}
this.$get = [function() {
return Logger;
}];
}).
controller('mainCtrl',function($scope, Logger) {
Logger("console.log로 출력하는 로그메시지");
Logger.debug("console.debug 출력하는 로그메시지");
});
PROVIDER
지시자의 모든 것
<body>
<div class="container" ng-controller="demoCtrl">
<panel title="헬로" click="close()">
<div>
<h2>환영합니다~</h2>
<p>웹프레임크 세미나</p>
</div>
</panel>
<panel title="헬로2">
<p>webframworks.kr 화이팅</p>
</panel>
</div>
</body>
app.html
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{title}}</h3>
</div>
<div class="panel-body" ng-transclude></div>
</div>
panel.tmpl.html
<script type="text/javascript">
angular.module('demo', []).
directive('panel', ['$log', function($log){
return {
scope: {
title : "@",
contents : "@",
},
restrict: 'AE',
templateUrl: 'panel.tmpl.html',
transclude: true,
link: function($scope, iElm, iAttrs, controller) {
$(iElm).find('.panel-heading').click(function () {
$(iElm).find('.panel-body').toggle();
})
}
};
}]);
}]);
</script>
app.js
싱글페이지 웹 어플리케이션
단일 페이지 웹 어플리케이션은 간단히 말해서 웹 어플리케이션을 사용하는 동안 웹
페이지를 리로드하지 않는 웹 어플리케이션을 의미
SINGLE PAGE APPLICATION
ngRoute 모듈
<!DOCTYPE html>
<html ng-app="routerApp">
<head>
<meta charset="UTF-8">
<title>라우터 데모 엡</title>
<link rel="stylesheet" href="libs/bootstrap/css/bootstrap.min.css">
<script type="text/javascript" src="libs/angular/angular.js"></script>
<script type="text/javascript" src="libs/angular/angular-route.js"></script>
<script type="text/javascript" src="routerApp.js"></script>
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<a class="brand" href="#">라우터 셈플</a>
<ul class="nav">
<li><a href="#home">홈</a></li>
<li><a href="#userList">사용자 관리</a></li>
</ul>
</div>
</div>
<ng-view></ng-view>
</div>
</body>
</html>
app.html
angular.module('routerApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/home', {templateUrl: 'views/home.html'})
.when('/userList', {templateUrl: 'views/userList.html', controller: 'userListCtrl'})
.otherwise({redirectTo: '/home'});
})
.controller('userListCtrl',function($scope) {
$scope.userList = [
{
name : '존',
email : 'john@gmail.com',
regDate : '2012-03-12'
},
{
name : '제시카',
email : 'jess@gmail.com',
regDate : '2012-03-12'
}
];
});
routeApp.js
AngularJS 란?
Google이 만든 웹 어플리케이션을 위한
Structural Framework
• 양방향 데이터 바인딩
• MVC 구조
• Template
• Directive를 통한 컴포넌트 재사용
• E2E 테스팅 및 Mocks
• 의존성 주입 (DI)
• Router
• ….
CRUD Apps 필수 기능 제공을 통한
(단일 페이지) 웹 어플리케이션 개발의 단순화
QnA
감사합니다.

Más contenido relacionado

La actualidad más candente

Event source 학습 내용 공유
Event source 학습 내용 공유Event source 학습 내용 공유
Event source 학습 내용 공유beom kyun choi
 
처음배우는 자바스크립트, 제이쿼리 #3
처음배우는 자바스크립트, 제이쿼리 #3처음배우는 자바스크립트, 제이쿼리 #3
처음배우는 자바스크립트, 제이쿼리 #3성일 한
 
목적이 부여된 에이전트 행동
목적이 부여된 에이전트 행동목적이 부여된 에이전트 행동
목적이 부여된 에이전트 행동Hyosung Jeon
 
Vuejs 시작하기
Vuejs 시작하기Vuejs 시작하기
Vuejs 시작하기성일 한
 
Node.js and react
Node.js and reactNode.js and react
Node.js and reactHyungKuIm
 
처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4성일 한
 

La actualidad más candente (7)

Event source 학습 내용 공유
Event source 학습 내용 공유Event source 학습 내용 공유
Event source 학습 내용 공유
 
처음배우는 자바스크립트, 제이쿼리 #3
처음배우는 자바스크립트, 제이쿼리 #3처음배우는 자바스크립트, 제이쿼리 #3
처음배우는 자바스크립트, 제이쿼리 #3
 
목적이 부여된 에이전트 행동
목적이 부여된 에이전트 행동목적이 부여된 에이전트 행동
목적이 부여된 에이전트 행동
 
Vuejs 시작하기
Vuejs 시작하기Vuejs 시작하기
Vuejs 시작하기
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4
 
진큐 오버뷰
진큐 오버뷰진큐 오버뷰
진큐 오버뷰
 

Destacado

Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점 Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점 WebFrameworks
 
Bootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapWebFrameworks
 
Celltrion Healthcare 102 weeks with Remsima(non-HCP)
Celltrion Healthcare 102 weeks with Remsima(non-HCP)Celltrion Healthcare 102 weeks with Remsima(non-HCP)
Celltrion Healthcare 102 weeks with Remsima(non-HCP)celltrionh
 
Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발Jin wook
 
React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기WebFrameworks
 
Webframeworks.kr의 소개
Webframeworks.kr의 소개Webframeworks.kr의 소개
Webframeworks.kr의 소개WebFrameworks
 
웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인
웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인
웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인WebFrameworks
 
Nodejs를 이용한 개발
Nodejs를 이용한 개발Nodejs를 이용한 개발
Nodejs를 이용한 개발WebFrameworks
 
위플래닛 발표자료 Meteor_js
위플래닛 발표자료 Meteor_js위플래닛 발표자료 Meteor_js
위플래닛 발표자료 Meteor_jsWebFrameworks
 
Meteor를 통해서 개발하는 웹어플리케이션 서비스
Meteor를 통해서 개발하는 웹어플리케이션 서비스Meteor를 통해서 개발하는 웹어플리케이션 서비스
Meteor를 통해서 개발하는 웹어플리케이션 서비스WebFrameworks
 
웹-프론트엔드 프레임워크를 고르기 위한 팁
웹-프론트엔드 프레임워크를 고르기 위한 팁웹-프론트엔드 프레임워크를 고르기 위한 팁
웹-프론트엔드 프레임워크를 고르기 위한 팁WebFrameworks
 

Destacado (13)

Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점 Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
Angular를 활용한 웹 프론트단 개발과 2.0에서 달라진점
 
Bootstrap과 UI-Bootstrap
Bootstrap과 UI-BootstrapBootstrap과 UI-Bootstrap
Bootstrap과 UI-Bootstrap
 
Celltrion Healthcare 102 weeks with Remsima(non-HCP)
Celltrion Healthcare 102 weeks with Remsima(non-HCP)Celltrion Healthcare 102 weeks with Remsima(non-HCP)
Celltrion Healthcare 102 weeks with Remsima(non-HCP)
 
Meteor2015 codelab
Meteor2015 codelab Meteor2015 codelab
Meteor2015 codelab
 
Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발
 
One-day-codelab
One-day-codelabOne-day-codelab
One-day-codelab
 
React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기React를 이용하여 멀티플랫폼에서 개발하기
React를 이용하여 멀티플랫폼에서 개발하기
 
Webframeworks.kr의 소개
Webframeworks.kr의 소개Webframeworks.kr의 소개
Webframeworks.kr의 소개
 
웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인
웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인
웹프레임워크를 이용하여 개발된 오픈소스 CMS프로젝트 샤인
 
Nodejs를 이용한 개발
Nodejs를 이용한 개발Nodejs를 이용한 개발
Nodejs를 이용한 개발
 
위플래닛 발표자료 Meteor_js
위플래닛 발표자료 Meteor_js위플래닛 발표자료 Meteor_js
위플래닛 발표자료 Meteor_js
 
Meteor를 통해서 개발하는 웹어플리케이션 서비스
Meteor를 통해서 개발하는 웹어플리케이션 서비스Meteor를 통해서 개발하는 웹어플리케이션 서비스
Meteor를 통해서 개발하는 웹어플리케이션 서비스
 
웹-프론트엔드 프레임워크를 고르기 위한 팁
웹-프론트엔드 프레임워크를 고르기 위한 팁웹-프론트엔드 프레임워크를 고르기 위한 팁
웹-프론트엔드 프레임워크를 고르기 위한 팁
 

Similar a Webframeworks angular js 세미나

Angular js quick start
Angular js quick startAngular js quick start
Angular js quick start정기 김
 
Cappuccino fundamental
Cappuccino fundamentalCappuccino fundamental
Cappuccino fundamentalJeongHun Byeon
 
HeadFisrt Servlet&JSP Chapter 3
HeadFisrt Servlet&JSP Chapter 3HeadFisrt Servlet&JSP Chapter 3
HeadFisrt Servlet&JSP Chapter 3J B
 
Nodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjsNodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjs기동 이
 
Ksug2015 jpa4 객체지향쿼리
Ksug2015 jpa4 객체지향쿼리Ksug2015 jpa4 객체지향쿼리
Ksug2015 jpa4 객체지향쿼리Younghan Kim
 
[D2 오픈세미나]5.robolectric 안드로이드 테스팅
[D2 오픈세미나]5.robolectric 안드로이드 테스팅[D2 오픈세미나]5.robolectric 안드로이드 테스팅
[D2 오픈세미나]5.robolectric 안드로이드 테스팅NAVER D2
 
Okjsp 13주년 발표자료: 생존 프로그래밍 Test
Okjsp 13주년 발표자료: 생존 프로그래밍 TestOkjsp 13주년 발표자료: 생존 프로그래밍 Test
Okjsp 13주년 발표자료: 생존 프로그래밍 Testbeom kyun choi
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Kim Hunmin
 
overview of spring4
overview of spring4overview of spring4
overview of spring4Arawn Park
 
Django와 flask
Django와 flaskDjango와 flask
Django와 flaskJiho Lee
 
2013 JCO tipJS.com JavaScript MVC framework
2013 JCO tipJS.com JavaScript MVC framework2013 JCO tipJS.com JavaScript MVC framework
2013 JCO tipJS.com JavaScript MVC frameworkSeung-Hyun PAEK
 
딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetectJunyi Song
 
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQLPgDay.Seoul
 
[115] clean fe development_윤지수
[115] clean fe development_윤지수[115] clean fe development_윤지수
[115] clean fe development_윤지수NAVER D2
 
보험케어.pptx
보험케어.pptx보험케어.pptx
보험케어.pptxjaeheon1
 
Android volley library
Android volley libraryAndroid volley library
Android volley library정인 주
 
GraphQL overview #2
GraphQL overview #2GraphQL overview #2
GraphQL overview #2기동 이
 

Similar a Webframeworks angular js 세미나 (20)

Angular js quick start
Angular js quick startAngular js quick start
Angular js quick start
 
Cappuccino fundamental
Cappuccino fundamentalCappuccino fundamental
Cappuccino fundamental
 
HeadFisrt Servlet&JSP Chapter 3
HeadFisrt Servlet&JSP Chapter 3HeadFisrt Servlet&JSP Chapter 3
HeadFisrt Servlet&JSP Chapter 3
 
시종설 1조
시종설 1조시종설 1조
시종설 1조
 
Nodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjsNodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjs
 
Ksug2015 jpa4 객체지향쿼리
Ksug2015 jpa4 객체지향쿼리Ksug2015 jpa4 객체지향쿼리
Ksug2015 jpa4 객체지향쿼리
 
[D2 오픈세미나]5.robolectric 안드로이드 테스팅
[D2 오픈세미나]5.robolectric 안드로이드 테스팅[D2 오픈세미나]5.robolectric 안드로이드 테스팅
[D2 오픈세미나]5.robolectric 안드로이드 테스팅
 
MVP 패턴 소개
MVP 패턴 소개MVP 패턴 소개
MVP 패턴 소개
 
Okjsp 13주년 발표자료: 생존 프로그래밍 Test
Okjsp 13주년 발표자료: 생존 프로그래밍 TestOkjsp 13주년 발표자료: 생존 프로그래밍 Test
Okjsp 13주년 발표자료: 생존 프로그래밍 Test
 
Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까? Facebook은 React를 왜 만들었을까?
Facebook은 React를 왜 만들었을까?
 
overview of spring4
overview of spring4overview of spring4
overview of spring4
 
Django와 flask
Django와 flaskDjango와 flask
Django와 flask
 
Nest js 101
Nest js 101Nest js 101
Nest js 101
 
2013 JCO tipJS.com JavaScript MVC framework
2013 JCO tipJS.com JavaScript MVC framework2013 JCO tipJS.com JavaScript MVC framework
2013 JCO tipJS.com JavaScript MVC framework
 
딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect딥러닝(Deep Learing) using DeepDetect
딥러닝(Deep Learing) using DeepDetect
 
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
[Pgday.Seoul 2021] 1. 예제로 살펴보는 포스트그레스큐엘의 독특한 SQL
 
[115] clean fe development_윤지수
[115] clean fe development_윤지수[115] clean fe development_윤지수
[115] clean fe development_윤지수
 
보험케어.pptx
보험케어.pptx보험케어.pptx
보험케어.pptx
 
Android volley library
Android volley libraryAndroid volley library
Android volley library
 
GraphQL overview #2
GraphQL overview #2GraphQL overview #2
GraphQL overview #2
 

Webframeworks angular js 세미나

  • 2. • GDG Korea WebTech 운영자 • 표준프레임워크 오픈 커미터 리더 • 시작하세요 AngularJS 프로그래밍 집필 • kt 연구소, IoT 플랫폼 개발 고재도
  • 5. <body> <div ng-controller="sampleCtrl"> 고객 목록 <ul> <li ng-repeat="user in userList"> <input type="number" ng-model="user.age"> {{user.name}} </li> </ul> <div>나이 합계 : {{userList[0].age + userList[1].age}}</div> </div> </body> $scope.userList = [ {name:'제이', age:25}, {name:'블레어', age:28} ]; 반복적인 데이터 표현 템플릿
  • 6.
  • 7. <input type="radio" ng-model="color" value="red"> 빨간색 <br> <input type="radio" ng-model="color" value="green"> 녹색 <br> <div ng-switch="color"> <div ng-switch-when="red" class="box red"></div> <div ng-switch-when="green" class="box green"></div> <div ng-switch-default="" class="box black"></div> </div> <div> 약관에 동의: <input type="checkbox" ng-model="checked" ng-init="checked=false"> <br> 동의하면 다음으로 진행됩니다. <button ng-if="checked">다음</button> </div> 조건적인 데이터 표현 템플릿
  • 8.
  • 9. <form name="sampleForm" ng-init="name = '철수'"> 이름 : <input type="text" name="name" ng-model="name" ng-maxlength="3" ng-required="true"> <span class="error" ng-show="sampleForm.name.$error.required">필수입력</span> <br> 핸드폰 번호: <input type="text" name="tel" ng-model="tel" ng-pattern="/^d{3}-d{3,4}-d{4}$/"> <span class="error" ng-show="sampleForm.tel.$error.pattern"> 000-0000-0000 </span> </form> 폼과 유효성 검사 템플릿
  • 10.
  • 11. <script type=“text/javascript"> function mainCtrl($scope){ $scope.message = ""; $scope.eventCnt = 0; $scope.handleEvt = function(message) { $scope.message = message; $scope.eventCnt++; } } </script> <body ng-controller="mainCtrl"> <div class="box" ng-click="handleEvt('박스 클릭됬다.')">click</div> <div class="box" ng-mousedown="handleEvt('박스 mousedown 이벤트 발생.')">mousedown</div> <div class="box" ng-mouseenter="handleEvt('박스 mouseenter 이벤트 발생.')">mouseenter</div> <div class="box" ng-mousemove="handleEvt('박스 mouseenter 이벤트 발생.')">mousemove</div> change : <input type="text" ng-model="inputText" ng-change="handleEvt('입력 박스의 값이 변경되었다.')"> keydown : <input type="text" ng-model="inputText2" ng-keydown="handleEvt($event.keyCode+'키코드 눌러짐')"> <p>{{message}} {{eventCnt}}</p> </body> 이벤트 처리 템플릿
  • 12.
  • 13. 템플릿 = 표현식 + 지시자
  • 14. 표현식 예제 • {{ 1+2 }} • {{ 3*10 | currency }} • {{ user.name }} 특징 • Scope 객체 기준으로 속성들을 검사한다. (window 로부터가 아니라…) • Null 에러를 무시한다. ({{a.b.c}} vs {{((a||{}).b||{}).c}}) • 조건문은 올 수 없다. • 필터들과 함께 쓰인다. ({{ 3*10 | currency }}) . Angular가 제대로 실행 되지 않을 경우 브라우저에 {{ 표현식 }}이 그대로 보이게 된다. ng-bind를 이용하면 이를 방지할 수 있다.
  • 15. a, form, input, ngApp, ngBind, ngChange, ngClass, ngClick, ngController, ngCloak, ngDbclick, ngDisabled, ngHide, ngHref, ngInclude, ngModel, ngMousedown, ngRepeat, ngView, ... BUILT-IN DIRECTIVE
  • 18. <body ng-controller="userMgtCtr"> <div> <label>부서</label> <select ng-model="sObj.deptId" ng-options="d.deptId as d.deptNm for d in deptList"> <option value="">선택</option> </select> <label>직급</label> <select ng-model="sObj.posId" ng-options="p.posId as p.posNm for p in posList"> <option value="">선택</option> </select> <button ng-click="find(sObj)">검색</button> </div> <div> <table class="table table-bordered table-hover"> <thead> <tr> <td>사번</td> <td>이름</td> <td>부서</td> </tr> </thead> <tbody> <tr ng-repeat="user in userList"> <td>{{user.userId}}</td> <td>{{user.userNm}}</td> <td>{{user.deptCd}}</td> </tr> </tbody> </table> </div> </body>
  • 19. angular.module(‘mvcApp’,[]) .controller('userMgtCtr', [‘$scope','$http', function ($scope, $http) { $scope.sObj={deptId:'',posId:''}; $scope.deptList = [ { deptId: '001', deptNm: '부서A'}, { deptId: '002', deptNm: '부서B'} ]; $scope.posList = [ { posId: '001', posNm: '사원'}, { posId: '002', posNm: '대리'} ]; $scope.find = function (sObj) { $http({ method: 'GET', url: 'user.json', params: { deptId: sObj.deptId, posId: sObj.posId } }) .success(function(data, status, headers, config) { $scope.userList = data; }); }; }]);
  • 22. 템플릿 뷰데이터 + <ul> <li ng-repeat="user in userList"> <input type="number" ng-model="user.age"> {{user.name}} </li> </ul> <div> 나이 합계 : {{userList[0].age + userList[1].age}} </div> = 사용자 화면 값 변경 $scope.userList = [ {name:'제이', age:25}, {name:'블레어', age:28} ];
  • 23.
  • 24. SCOPE • 뷰와 컨트롤러를 이어주는 단위 • 모델의 개념
  • 28. 모듈 Module 해당 모듈이 사용하는 다른 모듈 문자열 배열로 작성 angular.moudle(‘UserMnge’) 모듈 함수를 2번째 인자가 없이 호출하면 등록된 모듈 인스턴스 반환
  • 29. 모듈 초기화 단계 angular.moudle(‘UserMnge’) .config(function(){ …. }); angular.moudle(‘UserMnge’) .run(function(){ …. } 모듈의 설정단계 - 서비스 프로바이더, 서비스 상수 주입 - 필터, 서비스, 펙토리, 벨류 주입 불가 모듈의 실행단계 - 필터, 서비스, 펙토리, 벨류 주입 (서비스 인스턴스 주입) - 메인 메소드와 같다고 보면됨
  • 30. 서비스 AngularJS의 컨트롤러, 지시자, 필터 그리고 다른 서비스에서 재사용 가능한 컴포넌트(대부분 UI 없이)를 서비스라 함 서비스는 다음과 같은 특징을 가짐 • 애플리케이션 공통 로직으로서의 서비스 • 싱글톤Singleton으로서의 서비스 • 커뮤니케이션 허브hub로서의 서비스 • 의존성 주입 대상Injectable Dependencies으로서의 서비스 서비스 생성 방법 app.constant app.value app.service app.factory app.config
  • 31. There are only three ways how an object or a function can get a hold of its dependencies: The dependency can be created, typically using the new operator. The dependency can be looked up by referring to a global variable. The dependency can be passed in to where it is needed. (출처 : http://docs.angularjs.org/guide/di) 강력한 의존 관계의 JavaScript 예제 의존관계 주입 #1
  • 32. Root Scope UserMnge $provide. factory(‘UserResource’, …) $injector (Dependency Injector) controller('mainCtrl', function($scope, UserResource) { … } ) mainCtrl Scope userList : Array 상속 find 주입 의존관계 주입 #2
  • 33. moduel.controller('mainCtrl',function($scope, UserResource) { … $scope.search = function() { … $scope.userList = UserResource.query({q : query}); }; $scope object UserResource Object • DI는 자신이 사용하는 오브젝트에 대한 선택과 생성 제어권을 외부로 넘기고 자신은 수동적으로 주입 받은 오브텍트를 사용하게 된다. • 이는 특히 Unit 테스트 작성에 큰 도움을 준다. 사용하는 오브젝트의 Mock을 만들어서 주입이 가능하기 때문이다. $scope Mock object UserResource Mock Object Unit Test 시실제 사용 시 의존관계 주입 #3
  • 34. angular.module('sampleApp', []). constant('PI', 3.14159). config(function (CalProvider, PI) { CalProvider.setDefaultRadius(5); console.log(PI); }). directive('circle', ['Cal','PI',function (Cal,PI) { //생략.. }]) CONSTANT
  • 35. angular.module('sampleApp', []). value('AppNm', 'demo app'). controller('mainCtrl',function($scope, AppNm) { $scope.appNm = AppNm; }); VALUE
  • 36. function Calculator () { this.lastValue = 0; this.add = function(a,b) { var returnV = a+b; this.lastValue = returnV; return returnV; }; this.minus = function(a,b) { var returnV = a-b; this.lastValue = returnV; return returnV; }; } angular.module('sampleApp', []). service('Calculator', Calculator). controller('mainCtrl',function($scope, Calculator) { $scope.val1 = Calculator.add(10,3); $scope.val2 = Calculator.minus(20,10); }); SERVICE
  • 37. app.factory('Foo', function(cnt) { return function(start) { this.cnt = start; this.inc = function(quan) { this.cnt += quan; }; }; }); app.controller('MainCtrl', function($scope, cnt, Foo) { $scope.cnt = name; $scope.foo = new Foo(1); $scope.inc = function() { $scope.foo.inc(1); }; }); FACTORY
  • 38. angular.module('sampleApp', []). provider('Logger', function () { function Logger(msg) { if(checkNativeLogger) console.log(msg); } Logger.debug = function(msg) { if(checkNativeLogger) console.debug(msg); }; Logger.info = function(msg) { if(checkNativeLogger) console.info(msg); }; function checkNativeLogger() { if(console) return true; return false; } this.$get = [function() { return Logger; }]; }). controller('mainCtrl',function($scope, Logger) { Logger("console.log로 출력하는 로그메시지"); Logger.debug("console.debug 출력하는 로그메시지"); }); PROVIDER
  • 40.
  • 41. <body> <div class="container" ng-controller="demoCtrl"> <panel title="헬로" click="close()"> <div> <h2>환영합니다~</h2> <p>웹프레임크 세미나</p> </div> </panel> <panel title="헬로2"> <p>webframworks.kr 화이팅</p> </panel> </div> </body> app.html
  • 42. <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">{{title}}</h3> </div> <div class="panel-body" ng-transclude></div> </div> panel.tmpl.html
  • 43. <script type="text/javascript"> angular.module('demo', []). directive('panel', ['$log', function($log){ return { scope: { title : "@", contents : "@", }, restrict: 'AE', templateUrl: 'panel.tmpl.html', transclude: true, link: function($scope, iElm, iAttrs, controller) { $(iElm).find('.panel-heading').click(function () { $(iElm).find('.panel-body').toggle(); }) } }; }]); }]); </script> app.js
  • 45. 단일 페이지 웹 어플리케이션은 간단히 말해서 웹 어플리케이션을 사용하는 동안 웹 페이지를 리로드하지 않는 웹 어플리케이션을 의미 SINGLE PAGE APPLICATION
  • 47. <!DOCTYPE html> <html ng-app="routerApp"> <head> <meta charset="UTF-8"> <title>라우터 데모 엡</title> <link rel="stylesheet" href="libs/bootstrap/css/bootstrap.min.css"> <script type="text/javascript" src="libs/angular/angular.js"></script> <script type="text/javascript" src="libs/angular/angular-route.js"></script> <script type="text/javascript" src="routerApp.js"></script> </head> <body> <div class="container"> <div class="navbar"> <div class="navbar-inner"> <a class="brand" href="#">라우터 셈플</a> <ul class="nav"> <li><a href="#home">홈</a></li> <li><a href="#userList">사용자 관리</a></li> </ul> </div> </div> <ng-view></ng-view> </div> </body> </html> app.html
  • 48. angular.module('routerApp', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/home', {templateUrl: 'views/home.html'}) .when('/userList', {templateUrl: 'views/userList.html', controller: 'userListCtrl'}) .otherwise({redirectTo: '/home'}); }) .controller('userListCtrl',function($scope) { $scope.userList = [ { name : '존', email : 'john@gmail.com', regDate : '2012-03-12' }, { name : '제시카', email : 'jess@gmail.com', regDate : '2012-03-12' } ]; }); routeApp.js
  • 50.
  • 51. Google이 만든 웹 어플리케이션을 위한 Structural Framework • 양방향 데이터 바인딩 • MVC 구조 • Template • Directive를 통한 컴포넌트 재사용 • E2E 테스팅 및 Mocks • 의존성 주입 (DI) • Router • …. CRUD Apps 필수 기능 제공을 통한 (단일 페이지) 웹 어플리케이션 개발의 단순화